/**
 * 모바일 판별 + 인지검사 가로모드 고정 (PRD §3.1.0)
 * - 실제 화면 방향(matchMedia)을 추적 → 세로면 "가로로 회전" 안내 오버레이
 * - 지원 브라우저(Screen Orientation API)면 OS 레벨 잠금 시도
 * - 데스크탑: 검사 진입 차단
 */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { supportsOrientationLock } from '../lib/browser';

export interface OrientationState {
  isMobile: boolean;
  isPortrait: boolean;
  /** OS 레벨 가로잠금(screen.orientation.lock) 가능 여부 — iOS는 항상 false */
  canLockOrientation: boolean;
  requestLock: () => Promise<void>;
  unlock: () => void;
}

function detectMobile(): boolean {
  const touchPoints = (navigator as any).maxTouchPoints > 0;
  const width = window.innerWidth <= 1024;
  const ua = /Android|iPhone|iPad|iPod|Mobile|webOS/i.test(navigator.userAgent);
  return touchPoints && (width || ua);
}

function queryLandscape(): boolean {
  return window.innerWidth >= window.innerHeight;
}

export function useOrientationLock(): OrientationState {
  const isMobile = detectMobile();
  const [isLandscape, setIsLandscape] = useState(queryLandscape);
  const [canLockOrientation] = useState(supportsOrientationLock);

  useEffect(() => {
    const mql = window.matchMedia('(orientation: landscape)');
    const onChange = () => setIsLandscape(queryLandscape());
    onChange();
    mql.addEventListener?.('change', onChange);
    window.addEventListener('resize', onChange);
    return () => {
      mql.removeEventListener?.('change', onChange);
      window.removeEventListener('resize', onChange);
    };
  }, []);

  const requestLock = useCallback(async () => {
    if (!isMobile) return;
    const orient: any = screen.orientation ?? (screen as any).msOrientation;
    if (orient?.lock) {
      try {
        await orient.lock('landscape');
      } catch {
        /* 미지원/거부 → 실제 회전 대기 */
      }
    }
    setIsLandscape(queryLandscape());
  }, [isMobile]);

  const unlock = useCallback(() => {
    const orient: any = screen.orientation ?? (screen as any).msOrientation;
    orient?.unlock?.().catch?.(() => {});
  }, []);

  // 반환 객체를 useMemo로 안정화한다. 렌더마다 새 객체를 반환하면
  // TestRunner의 `[orient, done]` effect가 렌더마다 재실행되어
  // requestFullscreen / orientation.lock / history.pushState가 반복 호출되고,
  // iOS Safari에서 백색 화면 프리즈를 유발한다. (수정사항-019)
  return useMemo(
    () => ({
      isMobile,
      isPortrait: isMobile && !isLandscape,
      canLockOrientation,
      requestLock,
      unlock,
    }),
    [isMobile, isLandscape, canLockOrientation, requestLock, unlock],
  );
}
