import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MobileBehaviorService {

  constructor() {
    this.initializeMobilePrevention();
  }

  /**
   * Inicializa prevenções de comportamento mobile
   */
  private initializeMobilePrevention(): void {
    if (this.isMobileDevice()) {
      this.preventZoom();
      this.preventPullToRefresh();
      this.optimizeTouch();
    }
  }

  /**
   * Previne zoom por JavaScript
   */
  private preventZoom(): void {
    // Previne zoom por pinch (dois dedos)
    document.addEventListener('gesturestart', this.preventGesture, { passive: false });
    document.addEventListener('gesturechange', this.preventGesture, { passive: false });
    document.addEventListener('gestureend', this.preventGesture, { passive: false });

    // Previne zoom por double-tap
    let lastTouchEnd = 0;
    document.addEventListener('touchend', (e) => {
      const now = (new Date()).getTime();
      if (now - lastTouchEnd <= 300) {
        e.preventDefault();
      }
      lastTouchEnd = now;
    }, { passive: false });

    // Previne zoom por Ctrl+scroll/pinch em desktop
    document.addEventListener('wheel', (e) => {
      if (e.ctrlKey) {
        e.preventDefault();
      }
    }, { passive: false });

    // Previne zoom por teclado (Ctrl +/-)
    document.addEventListener('keydown', (e) => {
      if ((e.ctrlKey || e.metaKey) && (e.key === '+' || e.key === '-' || e.key === '0')) {
        e.preventDefault();
      }
    });
  }

  /**
   * Previne gesto de zoom
   */
  private preventGesture(e: Event): void {
    e.preventDefault();
  }

  /**
   * Previne pull-to-refresh no mobile
   */
  private preventPullToRefresh(): void {
    document.addEventListener('touchstart', (e) => {
      if (e.touches.length !== 1) return;
      
      const touch = e.touches[0];
      const target = e.target as Element;
      
      // Previne pull-to-refresh apenas se não estiver em uma área scrollável
      if (window.scrollY === 0 && !this.isScrollableElement(target)) {
        const preventPull = (te: TouchEvent) => {
          const currentTouch = te.touches[0];
          if (currentTouch.clientY > touch.clientY) {
            te.preventDefault();
          }
        };
        
        document.addEventListener('touchmove', preventPull, { passive: false });
        document.addEventListener('touchend', () => {
          document.removeEventListener('touchmove', preventPull);
        }, { once: true });
      }
    }, { passive: false });
  }

  /**
   * Otimiza comportamento de touch
   */
  private optimizeTouch(): void {
    // Remove delay de 300ms em iOS
    document.addEventListener('touchstart', () => {}, { passive: true });
    
    // Melhora scroll em iOS (com type assertion para propriedade webkit)
    (document.body.style as any).webkitOverflowScrolling = 'touch';
  }

  /**
   * Verifica se elemento é scrollável
   */
  private isScrollableElement(element: Element): boolean {
    const scrollableSelectors = [
      '.data-table-container',
      '.mat-drawer-content',
      '.mat-sidenav-content',
      '.scrollable',
      '[data-scrollable]'
    ];
    
    return scrollableSelectors.some(selector => 
      element.closest(selector) !== null
    );
  }

  /**
   * Detecta se é dispositivo mobile
   */
  private isMobileDevice(): boolean {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
           ('ontouchstart' in window) ||
           (navigator.maxTouchPoints > 0);
  }

  /**
   * Detecta se está em modo PWA
   */
  public isPWAMode(): boolean {
    return window.matchMedia('(display-mode: standalone)').matches ||
           window.matchMedia('(display-mode: fullscreen)').matches ||
           (window.navigator as any).standalone === true;
  }

  /**
   * Força orientação portrait (se necessário)
   */
  public lockToPortrait(): void {
    if ('screen' in window && 'orientation' in (window.screen as any)) {
      const screen = window.screen as any;
      if (screen.orientation && screen.orientation.lock) {
        screen.orientation.lock('portrait').catch((err: any) => {
          console.warn('Não foi possível bloquear orientação:', err);
        });
      }
    }
  }

  /**
   * Informações do dispositivo para debug
   */
  public getDeviceInfo(): any {
    return {
      isMobile: this.isMobileDevice(),
      isPWA: this.isPWAMode(),
      userAgent: navigator.userAgent,
      touchPoints: navigator.maxTouchPoints,
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight,
        devicePixelRatio: window.devicePixelRatio
      },
      safeArea: {
        top: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-top)'),
        bottom: getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-bottom)')
      }
    };
  }
} 