/**
 * Badge Notification System
 * Sends notifications when players unlock badges with celebration animations
 */

import { notifyOwner } from './_core/notification.ts';

export interface BadgeUnlockEvent {
  userId: string;
  badgeId: string;
  badgeName: string;
  badgeIcon: string;
  rarity: 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary';
  cosmetics?: string[];
  timestamp: Date;
}

export class BadgeNotifications {
  /**
   * Send badge unlock notification
   */
  static async notifyBadgeUnlock(event: BadgeUnlockEvent): Promise<void> {
    const rarityMessages: Record<string, { title: string; emoji: string }> = {
      common: { title: 'Badge Unlocked!', emoji: '🎖️' },
      uncommon: { title: 'Badge Unlocked!', emoji: '⭐' },
      rare: { title: 'Rare Badge Unlocked!', emoji: '✨' },
      epic: { title: 'Epic Badge Unlocked!', emoji: '🌟' },
      legendary: { title: 'Legendary Badge Unlocked!', emoji: '👑' },
    };

    const message = rarityMessages[event.rarity] || rarityMessages.common;

    // Send in-app notification
    await notifyOwner({
      title: `${message.emoji} ${message.title}`,
      content: `You've unlocked the "${event.badgeName}" badge! ${event.badgeIcon}`,
    });

    // Send special notification for rare+ badges
    if (['rare', 'epic', 'legendary'].includes(event.rarity)) {
      await this.sendCelebrationNotification(event);
    }

    // Send cosmetic unlock notification if applicable
    if (event.cosmetics && event.cosmetics.length > 0) {
      await this.sendCosmeticUnlockNotification(event);
    }
  }

  /**
   * Send celebration notification for rare badges
   */
  private static async sendCelebrationNotification(event: BadgeUnlockEvent): Promise<void> {
    const celebrations: Record<string, string> = {
      rare: '🎉 You earned a rare badge!',
      epic: '🎊 You earned an epic badge!',
      legendary: '🏆 You earned a legendary badge!',
    };

    const message = celebrations[event.rarity];
    if (message) {
      await notifyOwner({
        title: 'Achievement Unlocked!',
        content: message,
      });
    }
  }

  /**
   * Send cosmetic unlock notification
   */
  private static async sendCosmeticUnlockNotification(event: BadgeUnlockEvent): Promise<void> {
    if (!event.cosmetics || event.cosmetics.length === 0) return;

    const cosmeticNames = event.cosmetics.join(', ');
    await notifyOwner({
      title: '🎁 Cosmetics Unlocked!',
      content: `You've unlocked cosmetics: ${cosmeticNames}`,
    });
  }

  /**
   * Send batch badge unlock notifications
   */
  static async notifyBatchBadgeUnlocks(events: BadgeUnlockEvent[]): Promise<void> {
    for (const event of events) {
      await this.notifyBadgeUnlock(event);
    }
  }

  /**
   * Get badge unlock animation config
   */
  static getAnimationConfig(rarity: string): {
    duration: number;
    scale: number;
    particles: number;
    sound: string;
  } {
    switch (rarity) {
      case 'legendary':
        return { duration: 2000, scale: 1.5, particles: 100, sound: 'legendary_unlock' };
      case 'epic':
        return { duration: 1500, scale: 1.3, particles: 75, sound: 'epic_unlock' };
      case 'rare':
        return { duration: 1200, scale: 1.2, particles: 50, sound: 'rare_unlock' };
      case 'uncommon':
        return { duration: 800, scale: 1.1, particles: 25, sound: 'uncommon_unlock' };
      default:
        return { duration: 600, scale: 1.05, particles: 10, sound: 'common_unlock' };
    }
  }

  /**
   * Get celebration message
   */
  static getCelebrationMessage(badgeName: string, rarity: string): string {
    const messages: Record<string, string[]> = {
      legendary: [
        `🏆 Legendary achievement! You've unlocked "${badgeName}"!`,
        `👑 You are truly elite! Legendary badge "${badgeName}" is yours!`,
        `⭐ Incredible! You've earned the legendary "${badgeName}" badge!`,
      ],
      epic: [
        `🌟 Epic! You've unlocked the "${badgeName}" badge!`,
        `✨ Awesome! The epic "${badgeName}" badge is now yours!`,
        `🎊 You've achieved the epic "${badgeName}" badge!`,
      ],
      rare: [
        `✨ Rare! You've unlocked the "${badgeName}" badge!`,
        `🎉 Great job! The rare "${badgeName}" badge is yours!`,
        `⭐ You've earned the rare "${badgeName}" badge!`,
      ],
      uncommon: [
        `⭐ Nice! You've unlocked the "${badgeName}" badge!`,
        `🎖️ You've earned the "${badgeName}" badge!`,
      ],
      common: [
        `🎖️ You've unlocked the "${badgeName}" badge!`,
        `📌 Badge earned: "${badgeName}"!`,
      ],
    };

    const categoryMessages = messages[rarity] || messages.common;
    return categoryMessages[Math.floor(Math.random() * categoryMessages.length)];
  }

  /**
   * Track badge unlock for analytics
   */
  static async trackBadgeUnlock(userId: string, badgeId: string, rarity: string): Promise<void> {
    // In production, log to analytics service
    console.log(`[Analytics] Badge unlock: user=${userId}, badge=${badgeId}, rarity=${rarity}`);
  }

  /**
   * Get badge unlock statistics
   */
  static async getBadgeUnlockStats(badgeId: string): Promise<{
    totalUnlocks: number;
    uniquePlayers: number;
    averageTimeToUnlock: number;
    mostCommonPath: string;
  }> {
    // In production, query badge_unlock_stats table
    return {
      totalUnlocks: 0,
      uniquePlayers: 0,
      averageTimeToUnlock: 0,
      mostCommonPath: '',
    };
  }

  /**
   * Check for badge unlock milestones
   */
  static async checkBadgeMilestones(userId: string, totalBadges: number): Promise<string[]> {
    const milestones: string[] = [];

    if (totalBadges === 5) {
      milestones.push('badge_collector_5');
    }
    if (totalBadges === 10) {
      milestones.push('badge_collector_10');
    }
    if (totalBadges === 16) {
      milestones.push('badge_collector_all');
    }

    return milestones;
  }
}
