const { createCanvas, loadImage } = require('canvas');

class PosterEditor {
  /**
   * Crea poster con testi sovrapposti (compatibile con tua API originale)
   */
  async createPoster(backgroundImageUrl, data) {
    const { titolo, data: eventDate, ora, luogo, contatti } = data;

    const width = 1080;
    const height = 1920;

    const canvas = createCanvas(width, height);
    const ctx = canvas.getContext('2d');

    // Carica e disegna background
    try {
      let img;
      if (backgroundImageUrl.startsWith('data:')) {
        img = await loadImage(backgroundImageUrl);
      } else {
        const fetch = require('node-fetch');
        const response = await fetch(backgroundImageUrl);
        const buffer = await response.buffer();
        img = await loadImage(buffer);
      }

      // Cover fit
      const imgRatio = img.width / img.height;
      const canvasRatio = width / height;

      let dw, dh, dx, dy;
      if (imgRatio > canvasRatio) {
        dh = height;
        dw = height * imgRatio;
        dx = (width - dw) / 2;
        dy = 0;
      } else {
        dw = width;
        dh = width / imgRatio;
        dx = 0;
        dy = (height - dh) / 2;
      }

      ctx.drawImage(img, dx, dy, dw, dh);
    } catch (e) {
      // Fallback colore solido
      ctx.fillStyle = '#1a1a2e';
      ctx.fillRect(0, 0, width, height);
    }

    // Overlay gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, 'rgba(0,0,0,0)');
    gradient.addColorStop(0.5, 'rgba(0,0,0,0.3)');
    gradient.addColorStop(1, 'rgba(0,0,0,0.85)');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);

    // Titolo
    if (titolo) {
      ctx.save();
      ctx.font = 'bold 68px Arial, sans-serif';
      ctx.fillStyle = '#ffffff';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.shadowColor = 'rgba(0,0,0,0.9)';
      ctx.shadowBlur = 20;
      ctx.shadowOffsetX = 3;
      ctx.shadowOffsetY = 3;

      // Word wrap manuale
      const maxWidth = width * 0.9;
      const lines = this._wrapText(ctx, titolo.toUpperCase(), maxWidth);
      const lineHeight = 80;
      const startY = height * 0.50 - ((lines.length - 1) * lineHeight) / 2;

      lines.forEach((line, i) => {
        ctx.fillText(line, width / 2, startY + i * lineHeight);
      });

      ctx.restore();
    }

    // Data e ora
    if (eventDate) {
      ctx.save();
      ctx.font = 'bold 44px Arial, sans-serif';
      ctx.fillStyle = '#ffd700';
      ctx.textAlign = 'center';
      ctx.shadowColor = 'rgba(0,0,0,0.8)';
      ctx.shadowBlur = 10;

      const dateText = ora ? `${eventDate} • ORE ${ora}` : eventDate;
      ctx.fillText(dateText.toUpperCase(), width / 2, height * 0.68);
      ctx.restore();
    }

    // Luogo
    if (luogo) {
      ctx.save();
      ctx.font = '600 30px Arial, sans-serif';
      ctx.fillStyle = '#ffffff';
      ctx.textAlign = 'center';
      ctx.fillText(`📍 ${luogo}`, width / 2, height * 0.76);
      ctx.restore();
    }

    // Contatti
    if (contatti) {
      ctx.save();
      ctx.font = '400 24px Arial, sans-serif';
      ctx.fillStyle = '#cccccc';
      ctx.textAlign = 'center';
      ctx.fillText(contatti, width / 2, height * 0.85);
      ctx.restore();
    }

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

  /**
   * Word wrap utility
   */
  _wrapText(ctx, text, maxWidth) {
    const words = text.split(' ');
    const lines = [];
    let currentLine = '';

    words.forEach(word => {
      const testLine = currentLine ? `${currentLine} ${word}` : word;
      const metrics = ctx.measureText(testLine);

      if (metrics.width > maxWidth && currentLine) {
        lines.push(currentLine);
        currentLine = word;
      } else {
        currentLine = testLine;
      }
    });

    if (currentLine) {
      lines.push(currentLine);
    }

    return lines;
  }
}

module.exports = new PosterEditor();