// Canvas-based image generation for marketing assets
// Note: This would typically run server-side with node-canvas or similar
// For browser-based generation, we'd use HTML5 Canvas API

interface ImageConfig {
  width: number;
  height: number;
  platform?: string;
  event: any;
  qrCode?: string;
  backgroundColor: string | string[];
  textColor: string;
  accentColor: string;
}

interface FlyerConfig {
  width: number;
  height: number;
  style: 'modern' | 'classic' | 'minimal';
  event: any;
  qrCode?: string;
  backgroundColor: string | string[];
  textColor: string;
  accentColor: string;
}

class CanvasImageGenerator {
  private canvas: HTMLCanvasElement | null = null;
  private ctx: CanvasRenderingContext2D | null = null;

  constructor() {
    // Initialize canvas if in browser environment
    if (typeof window !== 'undefined') {
      this.canvas = document.createElement('canvas');
      this.ctx = this.canvas.getContext('2d');
    }
  }

  /**
   * Generate social media image
   */
  async generateSocialImage(config: ImageConfig): Promise<string> {
    if (!this.canvas || !this.ctx) {
      // Return placeholder URL for SSR or fallback
      return this.generatePlaceholderImage(config);
    }

    this.canvas.width = config.width;
    this.canvas.height = config.height;

    // Clear canvas
    this.ctx.clearRect(0, 0, config.width, config.height);

    // Draw background
    await this.drawBackground(config);

    // Draw event title
    this.drawEventTitle(config);

    // Draw event details
    this.drawEventDetails(config);

    // Draw QR code if provided
    if (config.qrCode) {
      await this.drawQRCode(config);
    }

    // Draw organization logo if available
    if (config.event.organizations?.logo) {
      await this.drawLogo(config);
    }

    // Draw platform-specific elements
    this.drawPlatformElements(config);

    return this.canvas.toDataURL('image/png');
  }

  /**
   * Generate flyer/poster image
   */
  async generateFlyer(config: FlyerConfig): Promise<string> {
    if (!this.canvas || !this.ctx) {
      return this.generatePlaceholderImage(config);
    }

    this.canvas.width = config.width;
    this.canvas.height = config.height;

    this.ctx.clearRect(0, 0, config.width, config.height);

    // Draw flyer-specific layout based on style
    switch (config.style) {
      case 'modern':
        await this.drawModernFlyer(config);
        break;
      case 'classic':
        await this.drawClassicFlyer(config);
        break;
      case 'minimal':
        await this.drawMinimalFlyer(config);
        break;
      default:
        await this.drawModernFlyer(config);
    }

    return this.canvas.toDataURL('image/png');
  }

  /**
   * Draw gradient or solid background
   */
  private async drawBackground(config: ImageConfig) {
    if (!this.ctx) return;

    if (Array.isArray(config.backgroundColor)) {
      // Create gradient
      const gradient = this.ctx.createLinearGradient(0, 0, config.width, config.height);
      config.backgroundColor.forEach((color, index) => {
        gradient.addColorStop(index / (config.backgroundColor.length - 1), color);
      });
      this.ctx.fillStyle = gradient;
    } else {
      this.ctx.fillStyle = config.backgroundColor;
    }

    this.ctx.fillRect(0, 0, config.width, config.height);
  }

  /**
   * Draw event title with proper sizing
   */
  private drawEventTitle(config: ImageConfig) {
    if (!this.ctx) return;

    const title = config.event.title;
    const maxWidth = config.width * 0.8;
    
    // Calculate font size based on canvas size and text length
    let fontSize = Math.min(config.width / 15, 48);
    this.ctx.font = `bold ${fontSize}px Arial, sans-serif`;
    
    // Adjust font size if text is too wide
    while (this.ctx.measureText(title).width > maxWidth && fontSize > 20) {
      fontSize -= 2;
      this.ctx.font = `bold ${fontSize}px Arial, sans-serif`;
    }

    this.ctx.fillStyle = config.textColor;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    // Draw title with multiple lines if needed
    this.wrapText(title, config.width / 2, config.height * 0.25, maxWidth, fontSize * 1.2);
  }

  /**
   * Draw event details (date, time, venue)
   */
  private drawEventDetails(config: ImageConfig) {
    if (!this.ctx) return;

    const event = config.event;
    const eventDate = new Date(event.start_time);
    const formattedDate = eventDate.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    const formattedTime = eventDate.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });

    const fontSize = Math.min(config.width / 25, 24);
    this.ctx.font = `${fontSize}px Arial, sans-serif`;
    this.ctx.fillStyle = config.textColor;
    this.ctx.textAlign = 'center';

    const y = config.height * 0.5;
    const lineHeight = fontSize * 1.5;

    // Draw date
    this.ctx.fillText(`📅 ${formattedDate}`, config.width / 2, y);
    // Draw time
    this.ctx.fillText(`⏰ ${formattedTime}`, config.width / 2, y + lineHeight);
    // Draw venue
    this.ctx.fillText(`📍 ${event.venue}`, config.width / 2, y + lineHeight * 2);
  }

  /**
   * Draw QR code
   */
  private async drawQRCode(config: ImageConfig) {
    if (!this.ctx || !config.qrCode) return;

    const qrSize = Math.min(config.width * 0.2, 150);
    const qrX = config.width - qrSize - 20;
    const qrY = config.height - qrSize - 20;

    // Create image from QR code data URL
    const qrImage = new Image();
    await new Promise((resolve) => {
      qrImage.onload = resolve;
      qrImage.src = config.qrCode!;
    });

    // Draw white background for QR code
    this.ctx.fillStyle = '#FFFFFF';
    this.ctx.fillRect(qrX - 10, qrY - 10, qrSize + 20, qrSize + 20);

    // Draw QR code
    this.ctx.drawImage(qrImage, qrX, qrY, qrSize, qrSize);

    // Add "Scan for Tickets" text
    this.ctx.fillStyle = config.textColor;
    this.ctx.font = `${Math.min(config.width / 40, 14)}px Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.fillText('Scan for Tickets', qrX + qrSize / 2, qrY + qrSize + 25);
  }

  /**
   * Draw organization logo
   */
  private async drawLogo(config: ImageConfig) {
    if (!this.ctx || !config.event.organizations?.logo) return;

    const logoSize = Math.min(config.width * 0.15, 80);
    const logoX = 20;
    const logoY = 20;

    try {
      const logoImage = new Image();
      await new Promise((resolve, reject) => {
        logoImage.onload = resolve;
        logoImage.onerror = reject;
        logoImage.src = config.event.organizations.logo;
      });

      this.ctx.drawImage(logoImage, logoX, logoY, logoSize, logoSize);
    } catch (error) {

    }
  }

  /**
   * Draw platform-specific elements
   */
  private drawPlatformElements(config: ImageConfig) {
    if (!this.ctx) return;

    // Add platform-specific call-to-action
    const cta = this.getPlatformCTA(config.platform);
    if (cta) {
      const fontSize = Math.min(config.width / 30, 20);
      this.ctx.font = `bold ${fontSize}px Arial, sans-serif`;
      this.ctx.fillStyle = config.accentColor;
      this.ctx.textAlign = 'center';
      this.ctx.fillText(cta, config.width / 2, config.height * 0.85);
    }
  }

  /**
   * Draw modern style flyer
   */
  private async drawModernFlyer(config: FlyerConfig) {
    // Modern flyer with geometric shapes and bold typography
    await this.drawBackground(config);
    
    // Add geometric accent shapes
    if (this.ctx) {
      this.ctx.fillStyle = config.accentColor + '20'; // Semi-transparent
      this.ctx.beginPath();
      this.ctx.arc(config.width * 0.1, config.height * 0.1, 100, 0, 2 * Math.PI);
      this.ctx.fill();
      
      this.ctx.beginPath();
      this.ctx.arc(config.width * 0.9, config.height * 0.9, 150, 0, 2 * Math.PI);
      this.ctx.fill();
    }

    this.drawEventTitle(config);
    this.drawEventDetails(config);
    
    if (config.qrCode) {
      await this.drawQRCode(config);
    }
  }

  /**
   * Draw classic style flyer
   */
  private async drawClassicFlyer(config: FlyerConfig) {
    // Classic flyer with elegant borders and traditional layout
    await this.drawBackground(config);
    
    // Add decorative border
    if (this.ctx) {
      this.ctx.strokeStyle = config.textColor;
      this.ctx.lineWidth = 3;
      this.ctx.strokeRect(20, 20, config.width - 40, config.height - 40);
    }

    this.drawEventTitle(config);
    this.drawEventDetails(config);
    
    if (config.qrCode) {
      await this.drawQRCode(config);
    }
  }

  /**
   * Draw minimal style flyer
   */
  private async drawMinimalFlyer(config: FlyerConfig) {
    // Minimal flyer with lots of whitespace and clean typography
    if (this.ctx) {
      this.ctx.fillStyle = '#FFFFFF';
      this.ctx.fillRect(0, 0, config.width, config.height);
    }

    // Override text color for minimal style
    const minimalConfig = { ...config, textColor: '#333333' };
    this.drawEventTitle(minimalConfig);
    this.drawEventDetails(minimalConfig);
    
    if (config.qrCode) {
      await this.drawQRCode(minimalConfig);
    }
  }

  /**
   * Wrap text to multiple lines
   */
  private wrapText(text: string, x: number, y: number, maxWidth: number, lineHeight: number) {
    if (!this.ctx) return;

    const words = text.split(' ');
    let line = '';
    let currentY = y;

    for (let n = 0; n < words.length; n++) {
      const testLine = line + words[n] + ' ';
      const metrics = this.ctx.measureText(testLine);
      const testWidth = metrics.width;

      if (testWidth > maxWidth && n > 0) {
        this.ctx.fillText(line, x, currentY);
        line = words[n] + ' ';
        currentY += lineHeight;
      } else {
        line = testLine;
      }
    }
    this.ctx.fillText(line, x, currentY);
  }

  /**
   * Get platform-specific call-to-action text
   */
  private getPlatformCTA(platform?: string): string {
    const ctas = {
      facebook: 'Get Your Tickets Now!',
      instagram: 'Link in Bio for Tickets',
      twitter: 'Click Link for Tickets',
      linkedin: 'Register Today'
    };

    return ctas[platform || 'facebook'] || 'Get Tickets';
  }

  /**
   * Generate placeholder image URL for SSR/fallback
   */
  private generatePlaceholderImage(config: any): string {
    // Return a placeholder service URL or data URI
    const width = config.width || 1200;
    const height = config.height || 630;
    const title = encodeURIComponent(config.event?.title || 'Event');
    
    // Using a placeholder service (you could replace with your own)
    return `https://via.placeholder.com/${width}x${height}/1877F2/FFFFFF?text=${title}`;
  }
}

export const canvasImageGenerator = new CanvasImageGenerator();