/**
 * `<skip-nav-ui>` — keyboard skip-link for WCAG 2.4.1 (Bypass Blocks).
 *
 * Renders an <a href="[target]"> that's visually hidden until focused,
 * then pops to the top-left of the viewport. On click, the browser
 * navigates to the target hash AND we move focus programmatically (the
 * native hash-jump doesn't always move focus; per spec it should land
 * on the target so a screen-reader resumes there).
 */

import { UIElement, html } from '../../core/element.js';

export class UISkipNav extends UIElement {
  static properties = {
    target: { type: String, default: '#main',                  reflect: true },
    text:   { type: String, default: 'Skip to main content',   reflect: true },
  };

  static template = ({ target, text }) => html`<a href="${target}" data-skip-link>${text}</a>`;

  connected() {
    super.connected();
    this.addEventListener('click', this.#onClick);
  }

  disconnected() {
    super.disconnected();
    this.removeEventListener('click', this.#onClick);
  }

  #onClick = (e) => {
    const link = e.target.closest('[data-skip-link]');
    if (!link) return;
    const id = this.target.replace(/^#/, '');
    const tgt = document.getElementById(id);
    if (!tgt) return;
    // Don't preventDefault — browser still updates the hash for the
    // back-button. But we ALSO focus the target so AT cursor moves there
    // (browser hash-jump scrolls but doesn't always move focus).
    queueMicrotask(() => {
      if (!tgt.hasAttribute('tabindex')) tgt.setAttribute('tabindex', '-1');
      tgt.focus({ preventScroll: false });
    });
  };
}
