import { DeesElement, html, property, customElement, css, type TemplateResult } from '@design.estate/dees-element';
import { idpElementStyles } from './tokens.js';

declare global {
  interface HTMLElementTagNameMap {
    'idp-toggle': IdpToggle;
  }
}

@customElement('idp-toggle')
export class IdpToggle extends DeesElement {
  public static demo = () => html`<idp-toggle checked></idp-toggle>`;
  public static demoGroups = ['idp.global v3 primitives'];

  @property({ type: Boolean, reflect: true })
  public accessor checked = false;

  @property({ type: Boolean, reflect: true })
  public accessor disabled = false;

  public static styles = [
    ...idpElementStyles,
    css`
      :host {
        display: inline-flex;
      }
      button {
        width: 36px;
        height: 20px;
        border: none;
        border-radius: 999px;
        padding: 2px;
        background: var(--idp-border);
        cursor: pointer;
        transition: background 150ms ease;
      }
      :host([checked]) button {
        background: var(--idp-accent);
      }
      :host([disabled]) button {
        opacity: 0.5;
        cursor: not-allowed;
      }
      .knob {
        width: 16px;
        height: 16px;
        border-radius: 999px;
        background: #fff;
        box-shadow: 0 1px 3px rgb(0 0 0 / 0.22);
        transition: transform 150ms ease;
      }
      :host([checked]) .knob {
        transform: translateX(16px);
      }
    `,
  ];

  private toggle() {
    if (this.disabled) {
      return;
    }
    this.checked = !this.checked;
    this.dispatchEvent(new CustomEvent('idp-toggle-change', {
      detail: { checked: this.checked },
      bubbles: true,
      composed: true,
    }));
  }

  public render(): TemplateResult {
    return html`
      <button role="switch" aria-checked=${this.checked} ?disabled=${this.disabled} @click=${this.toggle}>
        <div class="knob"></div>
      </button>
    `;
  }
}
