/**
 * Base class for BreakPilot Web Components
 */

import { ComplianceClient } from '@breakpilot/compliance-sdk-core'

export abstract class BreakPilotElement extends HTMLElement {
  protected client: ComplianceClient | null = null
  protected shadow: ShadowRoot

  constructor() {
    super()
    this.shadow = this.attachShadow({ mode: 'open' })
  }

  connectedCallback(): void {
    this.initializeClient()
    this.render()
  }

  disconnectedCallback(): void {
    this.cleanup()
  }

  attributeChangedCallback(
    name: string,
    _oldValue: string | null,
    _newValue: string | null
  ): void {
    if (name === 'api-key' || name === 'api-endpoint') {
      this.initializeClient()
    }
    this.render()
  }

  protected initializeClient(): void {
    const apiKey = this.getAttribute('api-key')
    const apiEndpoint =
      this.getAttribute('api-endpoint') || 'https://compliance.breakpilot.app/api/v1'
    const tenantId = this.getAttribute('tenant-id') || ''

    if (apiKey) {
      this.client = new ComplianceClient({
        apiKey,
        apiEndpoint,
        tenantId,
      })
    }
  }

  protected abstract render(): void
  protected cleanup(): void {}

  protected createStyles(css: string): HTMLStyleElement {
    const style = document.createElement('style')
    style.textContent = css
    return style
  }

  protected emit<T>(eventName: string, detail: T): void {
    this.dispatchEvent(
      new CustomEvent(eventName, {
        detail,
        bubbles: true,
        composed: true,
      })
    )
  }
}

// Common styles
export const COMMON_STYLES = `
  :host {
    display: block;
    font-family: system-ui, -apple-system, sans-serif;
    font-size: 14px;
    line-height: 1.5;
    box-sizing: border-box;
  }

  *, *::before, *::after {
    box-sizing: inherit;
  }

  button {
    font-family: inherit;
    font-size: inherit;
    cursor: pointer;
  }

  input, textarea {
    font-family: inherit;
    font-size: inherit;
  }
`
