import { LitElement, html, nothing, CSSResultArray } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-color-swatch.css';

 
@customElement('nile-color-swatch')
export class NileColorSwatch extends LitElement {
  static get styles(): CSSResultArray {
    return [styles];
  }

  /** The hex color this swatch represents. */
  @property({ type: String, reflect: true })color = '#000000';

  /** Whether this swatch is the currently selected color. */
  @property({ type: Boolean, reflect: true })active = false;

 
  private _tickColor(): string {
    const hex = this.color.replace('#', '');
  
    if (hex.length !== 6) {
      return '#FFFFFF';
    }
  
    const r = parseInt(hex.substring(0, 2), 16) / 255;
    const g = parseInt(hex.substring(2, 4), 16) / 255;
    const b = parseInt(hex.substring(4, 6), 16) / 255;
  
    const toLinear = (c: number) =>
      c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  
    const R = toLinear(r);
    const G = toLinear(g);
    const B = toLinear(b);
  
    const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
  
    const contrastWithWhite = (1.05) / (luminance + 0.05);
    const contrastWithBlack = (luminance + 0.05) / 0.05;
    return contrastWithWhite > contrastWithBlack ? '#FFFFFF' : '#111827';
  }

  render() {
    const cls = `swatch${this.active ? ' swatch--active' : ''}`;
    const tickColor = this._tickColor();
    return html`
      <button
        class=${cls}
        part="base"
        type="button"
        aria-pressed=${this.active ? 'true' : 'false'}
        aria-label=${this.color}
      >
        <span class="swatch__fill" style="background:${this.color}"></span>
        ${this.active
          ? html`
              <span class="swatch__check">
                <nile-glyph name="tick" color=${tickColor}></nile-glyph>
              </span>
            `
          : nothing}
      </button>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'nile-color-swatch': NileColorSwatch;
  }
}
