import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';

type PromptState = 'look-up' | 'look-around';

@Component({
  selector: 'app-ar-prompt',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './ar-prompt.component.html',
  styleUrls: ['./ar-prompt.component.css']
})
export class ArPromptComponent implements OnInit, OnDestroy {
  
  private readonly ANGLE_THRESHOLD = 45;
  public currentState: PromptState = 'look-up';
  
  private deviceOrientationHandler: (event: DeviceOrientationEvent) => void;

  constructor(private cdr: ChangeDetectorRef) {
    this.deviceOrientationHandler = this.handleDeviceOrientation.bind(this);
  }

  ngOnInit(): void {
    window.addEventListener('deviceorientation', this.deviceOrientationHandler, true);
  }

  ngOnDestroy(): void {
    window.removeEventListener('deviceorientation', this.deviceOrientationHandler, true);
  }

  private handleDeviceOrientation(event: DeviceOrientationEvent): void {
    const beta = event.beta;

    if (beta === null) return;

    const newState = beta > this.ANGLE_THRESHOLD ? 'look-around' : 'look-up';

    if (newState !== this.currentState) {
      this.currentState = newState;
      this.cdr.detectChanges();
    }
  }
}
