import { html, LitElement, nothing, type TemplateResult } from 'lit'
import { Router } from '@civility/ui'
import { icon } from '../utils/icon.ts'

/**
 * Page header: title, and an optional back button.
 *
 * A local replacement for `ui-header-content`, which renders its back arrow
 * through `ui-icon` — an `<img>` inside a shadow root. An SVG loaded that way
 * can't inherit `currentColor` and can't be reached by our CSS, so the arrow
 * stayed black and vanished against a dark theme. (`ui-icon` documents a
 * `--ui-icon-color` property, but its stylesheet never uses it.) Rendering
 * the arrow through {@link icon} instead makes it follow the theme like
 * everything else.
 */
export class MHeader extends LitElement {
  static override properties = {
    heading: {},
    back: { type: Boolean },
    fallbackHref: { attribute: 'fallback-href' },
  }

  declare heading: string
  declare back: boolean
  declare fallbackHref: string

  constructor() {
    super()
    this.heading = ''
    this.back = false
    this.fallbackHref = '#!/'
  }

  protected override createRenderRoot() {
    return this
  }

  override render(): TemplateResult {
    return html`
      ${this.back
        ? html`
          <button
            class="header-back"
            aria-label="Go back"
            @click="${() => Router.goBack(this.fallbackHref)}"
          >
            ${icon('arrow-left', '20px')}
          </button>
        `
        : nothing}
      <h1>${this.heading}</h1>
      <div class="header-actions"></div>
    `
  }
}

customElements.define('m-header', MHeader)
