import { Component, Input, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { A11yConfigService } from '../../services/a11y-config';

export interface SkipLink {
  href: string;
  text: string;
  ariaLabel?: string;
}

@Component({
  selector: 'ui-skip-links',
  standalone: true,
  imports: [CommonModule],
  template: `
    <nav 
      class="skip-links" 
      [class.skip-links--after-header]="position === 'after-header'"
      role="navigation"
      aria-label="Skip navigation links"
    >
      @for (link of skipLinks; track link.href) {
        <a 
          class="skip-link"
          [href]="link.href"
          [attr.aria-label]="link.ariaLabel || link.text"
          (click)="handleSkipLinkClick($event, link.href)"
        >
          {{ link.text }}
        </a>
      }
    </nav>
  `,
  styles: [`
    .skip-links {
      position: fixed;
      top: 0;
      left: 0;
      z-index: 10000;
    }

    .skip-links--after-header {
      position: relative;
      display: block;
      background: var(--a11y-skip-link-bg, #fff);
      border-bottom: 1px solid var(--a11y-skip-link-border, #ccc);
      padding: 0.5rem;
    }

    .skip-link {
      position: absolute;
      top: -40px;
      left: 6px;
      background: var(--a11y-skip-link-bg, #fff);
      color: var(--a11y-skip-link-color, #000);
      padding: 0.5rem 1rem;
      text-decoration: none;
      border: 1px solid var(--a11y-skip-link-border, #007bff);
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      opacity: 0;
      pointer-events: none;
      transform: translateY(-10px);
      transition: all 0.15s ease-out;
      font-weight: 500;
      white-space: nowrap;
    }

    .skip-link:focus {
      top: 6px;
      opacity: 1;
      pointer-events: auto;
      transform: translateY(0);
      outline: 2px solid var(--a11y-focus-color, #007bff);
      outline-offset: 2px;
    }

    .skip-link:nth-child(2):focus {
      top: 50px;
    }

    .skip-link:nth-child(3):focus {
      top: 94px;
    }

    .skip-link:nth-child(4):focus {
      top: 138px;
    }

    .skip-links--after-header .skip-link {
      position: static;
      display: inline-block;
      margin-right: 1rem;
      opacity: 1;
      pointer-events: auto;
      transform: none;
      transition: background-color 0.15s ease-out;
    }

    .skip-links--after-header .skip-link:hover,
    .skip-links--after-header .skip-link:focus {
      background-color: var(--a11y-focus-ring-color, rgba(0, 123, 255, 0.1));
    }

    @media (prefers-contrast: high) {
      .skip-link {
        background: ButtonFace;
        color: ButtonText;
        border-color: ButtonText;
        outline-color: Highlight;
      }
    }

    @media (prefers-reduced-motion: reduce) {
      .skip-link {
        transition-duration: 0.01s;
      }
    }
  `]
})
export class SkipLinksComponent implements OnInit {
  private config = inject(A11yConfigService);

  @Input() skipLinks: SkipLink[] = [];
  @Input() position: 'top' | 'after-header' = 'top';
  @Input() showOnFocus = true;

  ngOnInit(): void {
    // Use default links from config if none provided
    if (this.skipLinks.length === 0) {
      const configLinks = this.config.getSection('skipLinks').links;
      if (configLinks) {
        this.skipLinks = configLinks.map(link => ({
          href: link.href,
          text: link.text,
          ariaLabel: `Skip to ${link.text.toLowerCase()}`
        }));
      }
    }

    // Use position from config if not explicitly set
    if (this.position === 'top') {
      const configPosition = this.config.getSection('skipLinks').position;
      if (configPosition) {
        this.position = configPosition;
      }
    }
  }

  /**
   * Handle skip link click to ensure proper focus management
   */
  handleSkipLinkClick(event: Event, href: string): void {
    event.preventDefault();
    
    const targetId = href.replace('#', '');
    const targetElement = document.getElementById(targetId);
    
    if (targetElement) {
      // Set tabindex to make element focusable if it's not naturally focusable
      const originalTabIndex = targetElement.getAttribute('tabindex');
      if (!this.isFocusable(targetElement)) {
        targetElement.setAttribute('tabindex', '-1');
      }
      
      // Focus the target element
      targetElement.focus();
      
      // Scroll to the element
      targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      
      // Restore original tabindex after focus
      if (originalTabIndex === null && !this.isFocusable(targetElement)) {
        setTimeout(() => {
          targetElement.removeAttribute('tabindex');
        }, 100);
      }

      this.config.log('Skip link activated', { href, targetId });
    } else {
      this.config.warn('Skip link target not found', { href, targetId });
    }
  }

  /**
   * Check if an element is naturally focusable
   */
  private isFocusable(element: HTMLElement): boolean {
    const focusableSelectors = [
      'a[href]',
      'button',
      'textarea',
      'input[type="text"]',
      'input[type="radio"]',
      'input[type="checkbox"]',
      'select',
      '[tabindex]:not([tabindex="-1"])'
    ];
    
    return focusableSelectors.some(selector => element.matches(selector)) ||
           element.getAttribute('contenteditable') === 'true';
  }
}