// activities/TrackOrientationActivity.ts
import Activity from './Activity';
import Locator from '../services/Locator';
import { ANALYTICS_EVENTS } from '../services';

/**
 * Tracks device orientation changes (portrait ↔ landscape) and reports them via analytics.
 */
export default class TrackOrientationActivity extends Activity {
  private lastOrientation: 'portrait' | 'landscape' | null = null;

  constructor() {
    super('TrackOrientationActivity');
  }

  override async execute(): Promise<void> {
    const getOrientation = (): 'portrait' | 'landscape' =>
      window.innerWidth > window.innerHeight ? 'landscape' : 'portrait';

    const track = (orientation: 'portrait' | 'landscape') => {
      Locator.analytics.track(
        orientation === 'landscape'
          ? ANALYTICS_EVENTS.ORIENTATION_LANDSCAPE
          : ANALYTICS_EVENTS.ORIENTATION_PORTRAIT,
        {
          width: window.innerWidth,
          height: window.innerHeight,
        },
      );
    };

    // Set initial orientation
    this.lastOrientation = getOrientation();
    track(this.lastOrientation);

    // Watch for changes
    window.addEventListener('resize', () => {
      const current = getOrientation();
      if (current !== this.lastOrientation) {
        this.lastOrientation = current;
        track(current);
      }
    });
  }
}
