/**
 * QieHall SDK TypeScript ESM Wrapper (v1.5.0)
 *
 * 适用于 Cocos Creator 3.x (assets/scripts/QieHallSDK.ts)、Vite / Webpack / Phaser / Pixi 等任意 IDE 工程。
 * - 在企鹅游戏大厅 / 造梦工坊中运行时，自动桥接宿主注入的 window.QieHall。
 * - 在本地 IDE 单独预览（无 window.QieHall）时，自动提供安全的 standalone fallback，零报错运行。
 */

export interface QieHallAppearance {
  skinId: string;
  hatId?: string;
  frameId?: string;
  [key: string]: unknown;
}

export interface QieHallSeat {
  seat: number;
  uid: string;
  nickname: string;
  avatar?: number;
  mmr?: number;
  coins?: number;
  appearance?: QieHallAppearance;
  isBot?: boolean;
  online?: boolean;
}

export interface QieHallDisplay {
  orientation: 'portrait' | 'landscape' | 'auto';
  hudMode: 'topbar' | 'capsule' | 'immersive';
  capsuleRect: { top: number; right: number; width: number; height: number };
  safeInsets: { top: number; right: number; bottom: number; left: number };
}

export interface QieHallContext {
  gameId: string;
  roomCode: string;
  selfSeat: number;
  isOnline: boolean;
  safePadding?: { top: number; bottom: number; visibleWidth: number; visibleHeight: number };
  display?: QieHallDisplay;
  seats: QieHallSeat[];
  initSnapshot?: Record<string, unknown>;
}

export type QieHallBotDifficulty = 'easy' | 'normal' | 'hard';

export interface QieHallGameConfig {
  gameId?: string;
  version?: string;
  compatVersion?: string;
  minCompatVersion?: string;
  minAppVersion?: string;
  minPlayers?: number;
  maxPlayers?: number;
  maxTeamSize?: number;
  defaultTurnSec?: number;
  rankMode?: string;
  supportBotFill?: boolean;
  botDifficulty?: string;
  botFillAfterSec?: number;
  botSelectableDifficulties?: string[];
  [key: string]: unknown;
}

export interface QieHallJoystickState {
  active: boolean;
  x: number;
  y: number;
  dx: number;
  dy: number;
  angle: number;
  magnitude: number;
  originX: number;
  originY: number;
}

export interface QieHallJoystickOptions {
  mode?: 'floating' | 'fixed';
  follow?: boolean;
  zone?: 'left' | 'right' | 'full' | HTMLElement;
  zoneRatio?: number;
  size?: number;
  knobSize?: number;
  maxRadius?: number;
  deadzone?: number;
  accentColor?: string;
  hideWhenIdle?: boolean;
  restLeft?: number;
  restBottom?: number;
  visible?: boolean;
  enabled?: boolean;
  canStart?: (e: PointerEvent) => boolean;
  onStart?: (state: QieHallJoystickState) => void;
  onChange?: (state: QieHallJoystickState) => void;
  onEnd?: (state: QieHallJoystickState) => void;
}

export interface QieHallJoystickController {
  getState(): QieHallJoystickState;
  setVisible(next: boolean): void;
  setEnabled(next: boolean): void;
  reset(): void;
  destroy(): void;
}

export type QieHallEventHandler = (eventName: string, payload: any) => void;

const DEFAULT_DISPLAY: QieHallDisplay = {
  orientation: 'portrait',
  hudMode: 'capsule',
  capsuleRect: { top: 12, right: 12, width: 88, height: 34 },
  safeInsets: { top: 0, right: 0, bottom: 0, left: 0 },
};

function createStandaloneContext(): QieHallContext {
  return {
    gameId: 'standalone',
    roomCode: '',
    selfSeat: 0,
    isOnline: false,
    safePadding: { top: 0, bottom: 0, visibleWidth: 390, visibleHeight: 844 },
    display: {
      orientation: DEFAULT_DISPLAY.orientation,
      hudMode: DEFAULT_DISPLAY.hudMode,
      capsuleRect: { ...DEFAULT_DISPLAY.capsuleRect },
      safeInsets: { ...DEFAULT_DISPLAY.safeInsets },
    },
    seats: [
      {
        seat: 0,
        uid: 'local_0',
        nickname: '本地玩家',
        avatar: 1,
        mmr: 1000,
        coins: 1000,
        appearance: { skinId: 'penguin_classic', hatId: '', frameId: '' },
        isBot: false,
        online: true,
      },
      {
        seat: 1,
        uid: 'local_bot',
        nickname: '企鹅陪练',
        avatar: 2,
        mmr: 1000,
        coins: 1000,
        appearance: { skinId: 'penguin_aurora', hatId: 'crown_gold' },
        isBot: true,
        online: true,
      },
    ],
    initSnapshot: { solo: true },
  };
}

let fallbackCtx: QieHallContext | null = null;
const fallbackEvents: QieHallEventHandler[] = [];

function getNativeSDK(): any {
  if (typeof window !== 'undefined' && (window as any).QieHall) {
    return (window as any).QieHall;
  }
  return null;
}

export const QieHallSDK = {
  version: '1.5.0',

  isInHall(): boolean {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.isInHall === 'function') {
      return Boolean(sdk.isInHall());
    }
    try {
      return typeof window !== 'undefined' && Boolean(window.parent && window.parent !== window);
    } catch {
      return false;
    }
  },

  init(onStart?: (ctx: QieHallContext) => void): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.init === 'function') {
      sdk.init(onStart);
      return;
    }
    if (!fallbackCtx) {
      fallbackCtx = createStandaloneContext();
    }
    if (typeof onStart === 'function') {
      setTimeout(() => onStart(fallbackCtx as QieHallContext), 0);
    }
  },

  ready(): Promise<QieHallContext> {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.ready === 'function') {
      return sdk.ready();
    }
    return new Promise((resolve) => {
      this.init(resolve);
    });
  },

  onEvent(cb: QieHallEventHandler): () => void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.onEvent === 'function') {
      return sdk.onEvent(cb);
    }
    if (typeof cb === 'function') {
      fallbackEvents.push(cb);
    }
    return () => {
      const idx = fallbackEvents.indexOf(cb);
      if (idx >= 0) fallbackEvents.splice(idx, 1);
    };
  },

  getContext(): QieHallContext | null {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getContext === 'function') {
      return sdk.getContext();
    }
    return fallbackCtx;
  },

  getGameConfig(): QieHallGameConfig {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getGameConfig === 'function') {
      return sdk.getGameConfig() || {};
    }
    return {};
  },

  getBotDifficulty(): QieHallBotDifficulty {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getBotDifficulty === 'function') {
      const diff = String(sdk.getBotDifficulty() || '').toLowerCase();
      if (diff === 'easy' || diff === 'normal' || diff === 'hard') {
        return diff;
      }
    }
    return 'normal';
  },

  getDisplay(): QieHallDisplay {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getDisplay === 'function') {
      return sdk.getDisplay();
    }
    return fallbackCtx?.display || DEFAULT_DISPLAY;
  },

  setHudMode(mode: 'topbar' | 'capsule' | 'immersive'): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.setHudMode === 'function') {
      sdk.setHudMode(mode);
    }
  },

  openHostMenu(): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.openHostMenu === 'function') {
      sdk.openHostMenu();
    }
  },

  submitScore(score: number, meta?: Record<string, unknown>): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.submitScore === 'function') {
      sdk.submitScore(score, meta);
    }
  },

  getSelfSeat(): number {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getSelfSeat === 'function') {
      return Number(sdk.getSelfSeat() || 0);
    }
    return fallbackCtx ? fallbackCtx.selfSeat : 0;
  },

  getSeats(): QieHallSeat[] {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getSeats === 'function') {
      return sdk.getSeats();
    }
    return fallbackCtx ? fallbackCtx.seats : [];
  },

  getAppearance(seat: number): QieHallAppearance {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.getAppearance === 'function') {
      return sdk.getAppearance(seat);
    }
    const found = (fallbackCtx?.seats || []).find((s) => Number(s.seat) === Number(seat));
    return found?.appearance || { skinId: 'penguin_classic' };
  },

  sendAction(action: string, data?: unknown): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.sendAction === 'function') {
      sdk.sendAction(action, data);
    }
  },

  broadcast(payload: unknown): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.broadcast === 'function') {
      sdk.broadcast(payload);
      return;
    }
    this.sendAction('broadcast', payload);
  },

  setKV(key: string, value: unknown): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.setKV === 'function') {
      sdk.setKV(key, value);
      return;
    }
    this.sendAction('set_kv', { key, value });
  },

  finish(winnerSeat: number | number[], reason?: string, revealOrSummary?: unknown, extra?: { winnerSeats?: number[]; rankings?: unknown[] }): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.finish === 'function') {
      sdk.finish(winnerSeat, reason, revealOrSummary, extra);
    }
  },

  requestRematch(): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.requestRematch === 'function') {
      sdk.requestRematch();
    }
  },

  leaveRoom(): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.leaveRoom === 'function') {
      sdk.leaveRoom();
    }
  },

  playSfx(name: string): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.playSfx === 'function') {
      sdk.playSfx(name);
    }
  },

  showToast(msg: string): void {
    const sdk = getNativeSDK();
    if (sdk && typeof sdk.showToast === 'function') {
      sdk.showToast(msg);
    }
  },

  controls: {
    createJoystick(opts?: QieHallJoystickOptions): QieHallJoystickController {
      const sdk = getNativeSDK();
      if (sdk && sdk.controls && typeof sdk.controls.createJoystick === 'function') {
        return sdk.controls.createJoystick(opts);
      }
      const empty: QieHallJoystickState = {
        active: false,
        x: 0,
        y: 0,
        dx: 0,
        dy: 0,
        angle: 0,
        magnitude: 0,
        originX: 0,
        originY: 0,
      };
      return {
        getState: () => ({ ...empty }),
        setVisible: () => {},
        setEnabled: () => {},
        reset: () => {},
        destroy: () => {},
      };
    },
  },
};

export default QieHallSDK;
