/**
 * Mobile App Configuration
 * React Native app setup for iOS and Android
 */

export interface MobileAppConfig {
  appName: string;
  appVersion: string;
  bundleId: string;
  packageName: string;
  apiBaseUrl: string;
  wsBaseUrl: string;
  features: MobileFeatures;
  permissions: MobilePermissions;
  analytics: AnalyticsConfig;
}

export interface MobileFeatures {
  offlineGameplay: boolean;
  pushNotifications: boolean;
  biometricAuth: boolean;
  darkMode: boolean;
  languageSupport: string[];
  maxOfflineGames: number;
  cacheSize: number; // MB
}

export interface MobilePermissions {
  camera: boolean;
  microphone: boolean;
  contacts: boolean;
  calendar: boolean;
  location: boolean;
  photos: boolean;
  notifications: boolean;
}

export interface AnalyticsConfig {
  enabled: boolean;
  trackingId: string;
  crashReporting: boolean;
  sessionTracking: boolean;
}

/**
 * Default mobile app configuration
 */
export const DEFAULT_MOBILE_CONFIG: MobileAppConfig = {
  appName: 'CoinKrazy',
  appVersion: '1.0.0',
  bundleId: 'com.coinkrazy.app',
  packageName: 'com.coinkrazy.app',
  apiBaseUrl: process.env.REACT_APP_API_URL || 'https://api.coinkrazy.com',
  wsBaseUrl: process.env.REACT_APP_WS_URL || 'wss://ws.coinkrazy.com',
  features: {
    offlineGameplay: true,
    pushNotifications: true,
    biometricAuth: true,
    darkMode: true,
    languageSupport: ['en', 'es', 'fr', 'de', 'zh', 'ja'],
    maxOfflineGames: 50,
    cacheSize: 500,
  },
  permissions: {
    camera: false,
    microphone: false,
    contacts: false,
    calendar: false,
    location: false,
    photos: true,
    notifications: true,
  },
  analytics: {
    enabled: true,
    trackingId: 'UA-XXXXXXXXX-X',
    crashReporting: true,
    sessionTracking: true,
  },
};

/**
 * Offline gameplay configuration
 */
export interface OfflineGameConfig {
  gameId: string;
  gameName: string;
  maxPlays: number;
  syncOnConnect: boolean;
  cacheExpiry: number; // hours
}

export interface OfflineGameState {
  gameId: string;
  plays: OfflineGamePlay[];
  lastSyncTime: Date;
  isSynced: boolean;
}

export interface OfflineGamePlay {
  id: string;
  gameId: string;
  stake: number;
  result: number;
  timestamp: Date;
  synced: boolean;
}

/**
 * Create offline game state
 */
export function createOfflineGameState(gameId: string): OfflineGameState {
  return {
    gameId,
    plays: [],
    lastSyncTime: new Date(),
    isSynced: true,
  };
}

/**
 * Add offline game play
 */
export function addOfflineGamePlay(
  state: OfflineGameState,
  stake: number,
  result: number
): OfflineGamePlay {
  const play: OfflineGamePlay = {
    id: `play_${gameId}_${Date.now()}`,
    gameId: state.gameId,
    stake,
    result,
    timestamp: new Date(),
    synced: false,
  };

  state.plays.push(play);
  state.isSynced = false;

  return play;
}

/**
 * Get offline plays pending sync
 */
export function getOfflinePlaysPendingSync(state: OfflineGameState): OfflineGamePlay[] {
  return state.plays.filter((p) => !p.synced);
}

/**
 * Mark offline plays as synced
 */
export function markOfflinePlaysAsSynced(state: OfflineGameState, playIds: string[]): void {
  state.plays.forEach((play) => {
    if (playIds.includes(play.id)) {
      play.synced = true;
    }
  });

  state.isSynced = state.plays.every((p) => p.synced);
  state.lastSyncTime = new Date();
}

/**
 * Clear old offline plays
 */
export function clearOldOfflinePlays(state: OfflineGameState, maxAgeHours: number): void {
  const cutoffTime = new Date(Date.now() - maxAgeHours * 60 * 60 * 1000);
  state.plays = state.plays.filter((p) => p.timestamp > cutoffTime);
}

/**
 * Mobile push notification configuration
 */
export interface MobilePushConfig {
  fcmServerKey: string;
  apnsKey: string;
  apnsCertificate: string;
  soundEnabled: boolean;
  vibrationEnabled: boolean;
  badgeEnabled: boolean;
}

/**
 * Mobile biometric authentication
 */
export interface BiometricConfig {
  enabled: boolean;
  faceRecognition: boolean;
  fingerprint: boolean;
  iris: boolean;
  fallbackToPin: boolean;
}

/**
 * Mobile app store configuration
 */
export interface AppStoreConfig {
  iosAppId: string;
  iosTeamId: string;
  androidPackageId: string;
  androidKeyHash: string;
  reviewUrl: string;
}

/**
 * Get platform-specific configuration
 */
export function getPlatformConfig(platform: 'ios' | 'android'): Partial<MobileAppConfig> {
  if (platform === 'ios') {
    return {
      bundleId: 'com.coinkrazy.app',
      permissions: {
        camera: false,
        microphone: false,
        contacts: false,
        calendar: false,
        location: false,
        photos: true,
        notifications: true,
      },
    };
  } else {
    return {
      packageName: 'com.coinkrazy.app',
      permissions: {
        camera: false,
        microphone: false,
        contacts: false,
        calendar: false,
        location: false,
        photos: true,
        notifications: true,
      },
    };
  }
}

/**
 * Mobile app version management
 */
export interface AppVersion {
  version: string;
  buildNumber: number;
  releaseDate: Date;
  minSupportedVersion: string;
  features: string[];
  bugFixes: string[];
  isForceUpdate: boolean;
}

export function compareVersions(v1: string, v2: string): number {
  const parts1 = v1.split('.').map(Number);
  const parts2 = v2.split('.').map(Number);

  for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
    const part1 = parts1[i] || 0;
    const part2 = parts2[i] || 0;

    if (part1 > part2) return 1;
    if (part1 < part2) return -1;
  }

  return 0;
}

/**
 * Check if update is required
 */
export function isUpdateRequired(currentVersion: string, minSupportedVersion: string): boolean {
  return compareVersions(currentVersion, minSupportedVersion) < 0;
}

/**
 * Mobile app deep linking
 */
export interface DeepLink {
  scheme: string;
  host: string;
  path: string;
  parameters: Record<string, string>;
}

export const DEEP_LINK_SCHEMES = {
  game: 'coinkrazy://game/:gameId',
  tournament: 'coinkrazy://tournament/:tournamentId',
  leaderboard: 'coinkrazy://leaderboard/:period',
  referral: 'coinkrazy://referral/:code',
  profile: 'coinkrazy://profile/:userId',
  chat: 'coinkrazy://chat/:roomId',
};

/**
 * Parse deep link
 */
export function parseDeepLink(url: string): DeepLink | null {
  try {
    const urlObj = new URL(url);
    return {
      scheme: urlObj.protocol.replace(':', ''),
      host: urlObj.hostname,
      path: urlObj.pathname,
      parameters: Object.fromEntries(urlObj.searchParams),
    };
  } catch {
    return null;
  }
}

/**
 * Mobile app performance metrics
 */
export interface PerformanceMetrics {
  appStartTime: number; // ms
  firstPaintTime: number; // ms
  timeToInteractive: number; // ms
  memoryUsage: number; // MB
  batteryUsage: number; // %
  networkLatency: number; // ms
}

/**
 * Mobile app crash reporting
 */
export interface CrashReport {
  id: string;
  timestamp: Date;
  errorMessage: string;
  stackTrace: string;
  deviceInfo: DeviceInfo;
  appVersion: string;
  userId?: number;
}

export interface DeviceInfo {
  osVersion: string;
  deviceModel: string;
  screenSize: string;
  locale: string;
  timezone: string;
}

export function createCrashReport(
  error: Error,
  deviceInfo: DeviceInfo,
  appVersion: string,
  userId?: number
): CrashReport {
  return {
    id: `crash_${Date.now()}`,
    timestamp: new Date(),
    errorMessage: error.message,
    stackTrace: error.stack || '',
    deviceInfo,
    appVersion,
    userId,
  };
}
