import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges, computed, signal } from '@angular/core';
import { SectionConfig } from '../../shared/models/config';
import { HeroSlideData, HeroWidgetData } from '../contracts/widget-data.contract';

const AUTOPLAY_INTERVAL_MS = 5000;

@Component({
  selector: 'app-hero-widget',
  standalone: true,
  imports: [CommonModule],
  template: `
    <section class="hero-widget">
      @if (activeSlide(); as slide) {
        <h1 class="hero-widget__title">{{ slide.title }}</h1>
        @if (slide.subtitle) {
          <p class="hero-widget__subtitle">{{ slide.subtitle }}</p>
        }
        @if (slide.ctaLabel) {
          <button type="button" class="hero-widget__cta" (click)="onCtaClick()">{{ slide.ctaLabel }}</button>
        }

        @if (allSlides().length > 1) {
          <div class="hero-widget__dots" role="tablist" aria-label="Slides">
            @for (dot of allSlides(); track $index) {
              <button
                type="button"
                class="hero-widget__dot"
                [class.hero-widget__dot--active]="$index === activeIndex()"
                role="tab"
                [attr.aria-selected]="$index === activeIndex()"
                [attr.aria-label]="'Slide ' + ($index + 1)"
                (click)="goTo($index)"
              ></button>
            }
          </div>
        }
      }
    </section>
  `,
  styles: [
    `
      .hero-widget {
        position: relative;
        padding: var(--space-xl, 32px);
        border-radius: var(--radius-lg, 16px);
        background: linear-gradient(135deg, var(--bg-secondary, #f5f5f5) 0%, var(--bg-tertiary, #eef1f0) 100%);
        animation: hero-widget-in 420ms ease-out both;
      }

      .hero-widget__title {
        margin: 0 0 var(--space-sm, 8px);
        font-size: 2rem;
        font-weight: 700;
        color: var(--text-primary, #1e3c38);
        animation: hero-widget-in 480ms ease-out 60ms both;
      }

      .hero-widget__subtitle {
        margin: 0 0 var(--space-lg, 24px);
        color: var(--text-secondary, #667a77);
        font-size: 1.05rem;
        animation: hero-widget-in 480ms ease-out 120ms both;
      }

      .hero-widget__cta {
        border: 1px solid transparent;
        border-radius: var(--radius-md, 12px);
        padding: 0.75rem 1.5rem;
        cursor: pointer;
        font-weight: 600;
        background: var(--primary-color, #497671);
        color: #fff;
        transition: transform var(--transition-normal, 180ms ease), box-shadow var(--transition-normal, 180ms ease), background-color var(--transition-normal, 180ms ease);
        animation: hero-widget-in 480ms ease-out 180ms both;

        &:hover {
          background: var(--primary-hover, #3d635f);
          transform: translateY(-2px);
          box-shadow: var(--shadow-md, 0 4px 12px rgba(0, 0, 0, 0.15));
        }

        &:active {
          transform: translateY(0);
        }

        &:focus-visible {
          outline: 2px solid var(--primary-color, #497671);
          outline-offset: 2px;
        }
      }

      .hero-widget__dots {
        display: flex;
        gap: 8px;
        margin-top: var(--space-lg, 24px);
      }

      .hero-widget__dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        border: none;
        background: rgba(0, 0, 0, 0.2);
        cursor: pointer;
        padding: 0;

        &--active { background: var(--primary-color, #497671); }
        &:focus-visible { outline: 2px solid var(--primary-color, #497671); outline-offset: 2px; }
      }

      @keyframes hero-widget-in {
        from { opacity: 0; transform: translateY(12px); }
        to { opacity: 1; transform: translateY(0); }
      }

      @media (prefers-reduced-motion: reduce) {
        .hero-widget,
        .hero-widget__title,
        .hero-widget__subtitle,
        .hero-widget__cta {
          animation: none;
        }

        .hero-widget__cta {
          transition: none;
        }
      }
    `
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeroWidgetComponent implements OnChanges, OnDestroy {
  @Input() section: SectionConfig | null = null;
  @Input() data: HeroWidgetData | null = null;

  @Output() ctaClicked = new EventEmitter<void>();

  readonly activeIndex = signal(0);
  private readonly dataSignal = signal<HeroWidgetData | null>(null);
  private autoplayHandle: ReturnType<typeof setInterval> | null = null;

  readonly allSlides = computed<HeroSlideData[]>(() => {
    const current = this.dataSignal();
    if (!current) {
      return [];
    }
    const primary: HeroSlideData = { title: current.title, subtitle: current.subtitle, ctaLabel: current.ctaLabel };
    return [primary, ...(current.slides ?? [])];
  });

  readonly activeSlide = computed<HeroSlideData | null>(() => this.allSlides()[this.activeIndex()] ?? null);

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['data']) {
      this.dataSignal.set(this.data);
      this.activeIndex.set(0);
      this.setupAutoplay();
    }
  }

  ngOnDestroy(): void {
    this.clearAutoplay();
  }

  goTo(index: number): void {
    this.activeIndex.set(index);
    this.setupAutoplay();
  }

  onCtaClick(): void {
    this.ctaClicked.emit();
  }

  private setupAutoplay(): void {
    this.clearAutoplay();
    const slides = this.allSlides();
    if (!this.data?.autoplay || slides.length <= 1) {
      return;
    }
    this.autoplayHandle = setInterval(() => {
      this.activeIndex.update(index => (index + 1) % slides.length);
    }, AUTOPLAY_INTERVAL_MS);
  }

  private clearAutoplay(): void {
    if (this.autoplayHandle !== null) {
      clearInterval(this.autoplayHandle);
      this.autoplayHandle = null;
    }
  }
}
