import {
  LitElement,
  html,
  CSSResultArray,
  TemplateResult,
} from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styles } from './nile-skeleton-loader.css';
import NileElement from '../internal/nile-element';

@customElement('nile-skeleton-loader')
export class NileSkeletonLoader extends NileElement {
  public static get styles(): CSSResultArray {
    return [styles];
  }

  @property({ reflect: true }) variant: 'text' | 'circular' | 'rectangular' | 'rounded' = 'text';

  @property({ type: String }) width: string | number = '';

  @property({ type: String }) height: string | number = '';

  @property({ type: String, attribute: 'border-radius' }) borderRadius = '';

  private formatDimension(value: string | number): string {
    if (!value) return '';
    if (typeof value === 'number') {
      return `${value}px`;
    }
    const trimmed = String(value).trim();
    if (/^\d+(\.\d+)?$/.test(trimmed)) {
      return `${trimmed}px`;
    }
    return trimmed;
  }

  private getComputedWidth(): string {
    const formattedWidth = this.formatDimension(this.width);
    if (formattedWidth) {
      return formattedWidth;
    }
    return this.variant === 'circular' ? '40px' : 'calc(100% - 20px)';
  }

  private getComputedHeight(): string {
    const formattedHeight = this.formatDimension(this.height);
    if (formattedHeight) {
      return formattedHeight;
    }
    if (this.variant === 'circular') {
      return '40px';
    }
    return this.variant === 'text' ? '1em' : '20px';
  }

  private getComputedBorderRadius(): string {
    if (this.borderRadius) {
      return this.borderRadius;
    }
    if (this.variant === 'circular') {
      return '50%';
    }
    if (this.variant === 'rounded') {
      return 'var(--nile-radius-radius-md, var(--ng-radius-md, 4px))';
    }
    if (this.variant === 'text') {
      return 'var(--nile-radius-radius-xs, var(--ng-radius-xs, 2px))';
    }
    return 'var(--nile-radius-radius-xs, var(--ng-radius-xs))';
  }

  public render(): TemplateResult {
    return html`
      <div
        part="base"
        class="skeleton-loader"
      >
        <div
          part="skeleton"
          class=${classMap({
            skeleton: true,
            'skeleton--text': this.variant === 'text',
            'skeleton--circular': this.variant === 'circular',
            'skeleton--rectangular': this.variant === 'rectangular',
            'skeleton--rounded': this.variant === 'rounded',
          })}
          style="
            width: ${this.getComputedWidth()};
            height: ${this.getComputedHeight()};
            border-radius: ${this.getComputedBorderRadius()};
          "
        ></div>
      </div>
    `;
  }
}

export default NileSkeletonLoader;

declare global {
  interface HTMLElementTagNameMap {
    'nile-skeleton-loader': NileSkeletonLoader;
  }
}

