import { PktElement } from '@/base-elements/element'
import { PktSlotController } from '@/controllers/pkt-slot-controller'
import { ref, Ref, createRef } from 'lit/directives/ref.js'
import { html, nothing } from 'lit'
import { classMap } from 'lit/directives/class-map.js'
import { customElement, property } from 'lit/decorators.js'
import specs from 'componentSpecs/link.json'
import '@/components/icon'

@customElement('pkt-link')
export class PktLink extends PktElement {
  defaultSlot: Ref<HTMLElement> = createRef()

  constructor() {
    super()
    this.slotController = new PktSlotController(this, this.defaultSlot)
  }

  /**
   * Element attributes
   */
  @property({ type: String, reflect: true }) href: string = specs.props.href.default
  @property({ type: String, reflect: true }) iconName: string | undefined = undefined
  @property({ type: String, reflect: true }) iconPosition: string | undefined = undefined
  @property({ type: Boolean, reflect: true }) external: boolean = specs.props.external.default
  @property({ type: String, reflect: true }) target: string | null = specs.props.target.default

  render() {
    const classes = {
      'pkt-link': true,
      'pkt-link--icon-left':
        (!!this.iconName && this.iconPosition === 'left') ||
        !!(this.iconName && !this.iconPosition),
      'pkt-link--icon-right': !!this.iconName && this.iconPosition === 'right',
      'pkt-link--external': this.external,
    }
    return html`<a
      class=${classMap(classes)}
      href=${this.href}
      .target=${this.target}
      .rel=${this.external ? 'noopener noreferrer' : nothing}
      >${this.iconName
        ? html`<pkt-icon name=${this.iconName} class="pkt-link__icon"></pkt-icon>`
        : ''} <span ${ref(this.defaultSlot)}>Link</span></a
    >`
  }
}
