class ScrollProgressController {
  private bar: HTMLElement | null = null;
  private rafId: number | null = null;
  private lastProgress = -1;

  constructor() {
    this.init();
  }

  private init(): void {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => this.setup());
    } else {
      this.setup();
    }
  }

  public refresh(): void {
    this.requestUpdate();
  }

  private setup(): void {
    this.bar = document.querySelector<HTMLElement>('[data-scroll-progress]');
    if (!this.bar) return;

    this.requestUpdate();

    window.addEventListener('scroll', () => this.requestUpdate(), { passive: true });
    window.addEventListener('resize', () => this.requestUpdate());
    window.addEventListener('load', () => this.requestUpdate());
    document.addEventListener('astro:page-load', () => this.requestUpdate());
  }

  private requestUpdate(): void {
    if (this.rafId !== null) return;
    this.rafId = window.requestAnimationFrame(() => this.updateProgress());
  }

  private updateProgress(): void {
    this.rafId = null;
    if (!this.bar) return;

    const scrollElement = document.scrollingElement || document.documentElement;
    const scrollHeight = scrollElement.scrollHeight - scrollElement.clientHeight;
    const progress = scrollHeight > 0 ? scrollElement.scrollTop / scrollHeight : 0;

    if (progress === this.lastProgress) {
      return;
    }

    this.lastProgress = progress;
    this.bar.style.transform = `scaleX(${progress})`;
    this.bar.style.opacity = progress > 0 ? '1' : '0';
  }
}

if (typeof window !== 'undefined') {
  if (!(window as any).__scrollProgressController) {
    (window as any).__scrollProgressController = new ScrollProgressController();
  } else {
    const controller = (window as any).__scrollProgressController as ScrollProgressController;
    controller.refresh();
  }
}
