import { LitElement, html } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { ComponentStatesMixin } from '../ComponentStatesMixin'
import { EventEmitterMixin } from '../EventEmitterMixin'
import { getIcon } from '../LucideDynamicLoader'
import { addMask } from '../util/svg'
import { unsafeSVG } from 'lit/directives/unsafe-svg.js'

import './index.css'

@customElement('btu-icon')
export default class Icon extends ComponentStatesMixin(
  EventEmitterMixin(LitElement),
) {
  static get tagName() {
    return 'BTU-ICON'
  }

  @property({ type: Number })
  public size = 20

  @property({ type: String, reflect: true })
  public fill = 'solid'

  @property({ type: String })
  public symbol = 'circle-dashed'

  private _getScaledSize() {
    const defaultSize = 24 // Lucide default size
    return this.size / defaultSize
  }

  async connectedCallback() {
    super.connectedCallback()
  }

  async disconnectedCallback() {
    super.disconnectedCallback()
  }

  createRenderRoot() {
    return this
  }

  render() {
    const data = getIcon(
      window.BRIGHTSPOT.icons?.materialToLucide?.[this.symbol] || this.symbol,
      this,
    )

    if (this.fill === 'gradient') {
      const scale = this._getScaledSize()
      this.style.setProperty('transform', `scale(${scale})`)
      this.style.setProperty('--mask-url', `url(#${this.symbol})`)
    }

    return html`${unsafeSVG(
      this.fill === 'gradient'
        ? addMask(data?.svg || '', this.symbol)
        : data?.svg || '',
    )}`
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'btu-icon': Icon
  }
}
