
const { createCanvas, loadImage, registerFont } = require('canvas');
const fs = require('fs').promises;
const path = require('path');
const sharp = require('sharp');

// Registra font personalizzati
const FONTS_DIR = process.env.FONTS_DIR || './fonts';

const registerFonts = async () => {
  const fontMappings = [
    { file: 'Montserrat-Black.ttf', family: 'Montserrat', weight: '900' },
    { file: 'Montserrat-Bold.ttf', family: 'Montserrat', weight: '700' },
    { file: 'Montserrat-Regular.ttf', family: 'Montserrat', weight: '400' },
    { file: 'BebasNeue-Regular.ttf', family: 'Bebas Neue', weight: '400' },
    { file: 'OpenSans-Bold.ttf', family: 'Open Sans', weight: '700' },
    { file: 'OpenSans-SemiBold.ttf', family: 'Open Sans', weight: '600' },
    { file: 'OpenSans-Regular.ttf', family: 'Open Sans', weight: '400' },
    { file: 'OpenSans-Light.ttf', family: 'Open Sans', weight: '300' },
    { file: 'PlayfairDisplay-Bold.ttf', family: 'Playfair Display', weight: '700' },
    { file: 'PlayfairDisplay-Regular.ttf', family: 'Playfair Display', weight: '400' }
  ];

  
  for (const font of fontMappings) {
    const fontPath = path.join(FONTS_DIR, font.file);
    try {
      await fs.access(fontPath);
      registerFont(fontPath, { family: font.family, weight: font.weight });
    } catch (e) {
      // Font non trovato, usa fallback
    }
  }
};

// Inizializza fonts al caricamento modulo
registerFonts().catch(console.warn);

class PosterRenderer {
  constructor() {
    this.version = '1.0.0';
  }

  /**
   * Render principale
   */
  async render(options) {
    const {
      template,
      content,
      assets,
      layerOverrides = {},
      outputDir,
      posterId
    } = options;

    const startTime = Date.now();

    // Dimensioni canvas
    const width = template.format?.width || 2480;
    const height = template.format?.height || 3508;

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

    // 1. Disegna background
    await this._drawBackground(ctx, template, assets, width, height);

    // 2. Ordina layer per zIndex
    const sortedLayers = [...(template.layers || [])]
      .sort((a, b) => (a.zIndex || 0) - (b.zIndex || 0));

    // 3. Disegna ogni layer
    for (const layer of sortedLayers) {
      if (layer.visible === false) continue;

      const override = layerOverrides[layer.id] || {};
      const mergedLayer = this._mergeLayerOverride(layer, override);

      await this._drawLayer(ctx, mergedLayer, content, assets, width, height, template);
    }

    // 4. Disegna loghi
    if (template.logoSlots?.enabled && assets?.logos?.length > 0) {
      await this._drawLogos(ctx, template.logoSlots, assets.logos, width, height);
    }

    // 5. Salva output
    await fs.mkdir(outputDir, { recursive: true });

    const baseName = `poster_${posterId}_${Date.now()}`;
    const pngPath = path.join(outputDir, `${baseName}.png`);
    const jpgPath = path.join(outputDir, `${baseName}.jpg`);

    // Salva PNG
    const pngBuffer = canvas.toBuffer('image/png');
    await fs.writeFile(pngPath, pngBuffer);

    // Salva JPG con Sharp (migliore qualità)
    await sharp(pngBuffer)
      .jpeg({ quality: 95, progressive: true })
      .toFile(jpgPath);

    const [pngStats, jpgStats] = await Promise.all([
      fs.stat(pngPath),
      fs.stat(jpgPath)
    ]);

    return {
      pngPath,
      jpgPath,
      pngSize: pngStats.size,
      jpgSize: jpgStats.size,
      dimensions: { width, height },
      duration: Date.now() - startTime,
      engineVersion: this.version
    };
  }

  /**
   * Disegna background
   */
  async _drawBackground(ctx, template, assets, width, height) {
    // Colore di sfondo base
    ctx.fillStyle = template.backgroundColor || '#1a1a2e';
    ctx.fillRect(0, 0, width, height);

    // Background image
    const bgAsset = assets?.backgroundImage;
    const bgLayer = template.layers?.find(l => l.type === 'backgroundImage');

    if (bgAsset?.url) {
      try {
        const img = await this._loadImageFromUrl(bgAsset.url);
        
        // Calcola dimensioni per cover
        const imgRatio = img.width / img.height;
        const canvasRatio = width / height;

        let drawWidth, drawHeight, drawX, drawY;

        if (imgRatio > canvasRatio) {
          drawHeight = height;
          drawWidth = height * imgRatio;
          drawX = (width - drawWidth) / 2;
          drawY = 0;
        } else {
          drawWidth = width;
          drawHeight = width / imgRatio;
          drawX = 0;
          drawY = (height - drawHeight) / 2;
        }

        // Applica blur se definito
        if (bgLayer?.style?.blur > 0) {
          ctx.filter = `blur(${bgLayer.style.blur}px)`;
        }

        ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
        ctx.filter = 'none';

        // Applica overlay gradient
        const overlay = bgLayer?.style?.overlay;
        if (overlay?.enabled) {
          this._drawOverlay(ctx, overlay, width, height);
        }
      } catch (e) {
        console.warn('Background image load failed:', e.message);
        // Usa fallback
        if (bgLayer?.fallback) {
          this._drawFallback(ctx, bgLayer.fallback, width, height);
        }
      }
    } else if (bgLayer?.fallback) {
      this._drawFallback(ctx, bgLayer.fallback, width, height);
    }
  }

  /**
   * Disegna overlay gradient
   */
  _drawOverlay(ctx, overlay, width, height) {
    if (overlay.type === 'solid') {
      ctx.fillStyle = overlay.color || 'rgba(0,0,0,0.5)';
      ctx.fillRect(0, 0, width, height);
      return;
    }

    // Gradient
    let gradient;
    const dir = overlay.direction || 'to-bottom';

    if (dir === 'to-bottom') {
      gradient = ctx.createLinearGradient(0, 0, 0, height);
    } else if (dir === 'to-top') {
      gradient = ctx.createLinearGradient(0, height, 0, 0);
    } else if (dir === 'to-right') {
      gradient = ctx.createLinearGradient(0, 0, width, 0);
    } else if (dir === 'to-left') {
      gradient = ctx.createLinearGradient(width, 0, 0, 0);
    } else if (dir === 'to-bottom-right') {
      gradient = ctx.createLinearGradient(0, 0, width, height);
    } else {
      gradient = ctx.createLinearGradient(0, 0, 0, height);
    }

    if (overlay.stops) {
      overlay.stops.forEach(stop => {
        gradient.addColorStop(stop.position, stop.color);
      });
    } else {
      gradient.addColorStop(0, 'rgba(0,0,0,0)');
      gradient.addColorStop(1, 'rgba(0,0,0,0.7)');
    }

    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);
  }

  /**
   * Disegna fallback
   */
  _drawFallback(ctx, fallback, width, height) {
    if (fallback.type === 'solid') {
      ctx.fillStyle = fallback.color || '#333333';
      ctx.fillRect(0, 0, width, height);
    } else if (fallback.type === 'gradient' && fallback.colors) {
      const gradient = ctx.createLinearGradient(0, 0, 0, height);
      fallback.colors.forEach((color, i) => {
        gradient.addColorStop(i / (fallback.colors.length - 1), color);
      });
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, width, height);
    }
  }

  /**
   * Disegna singolo layer
   */
  async _drawLayer(ctx, layer, content, assets, canvasWidth, canvasHeight, template) {
    const pos = this._calculatePosition(layer.position, layer.anchor, canvasWidth, canvasHeight);

    switch (layer.type) {
      case 'backgroundImage':
        // Già gestito in _drawBackground
        break;

      case 'mainImage':
        await this._drawMainImage(ctx, assets?.mainImage, pos, layer.style);
        break;

      case 'title':
        this._drawText(ctx, content?.title, pos, layer.style, template.palette);
        break;

      case 'subtitle':
        this._drawText(ctx, content?.subtitle, pos, layer.style, template.palette);
        break;

      case 'eventDate':
        const dateText = content?.eventTime 
          ? `${content.eventDate} • ${content.eventTime}`
          : content?.eventDate;
        this._drawText(ctx, dateText, pos, layer.style, template.palette);
        break;

      case 'eventTime':
        this._drawText(ctx, content?.eventTime, pos, layer.style, template.palette);
        break;

      case 'location':
        this._drawTextWithIcon(ctx, content?.location, pos, layer, template.palette);
        break;

      case 'contacts':
        this._drawText(ctx, content?.contacts, pos, layer.style, template.palette);
        break;

      case 'extraText':
        const extraTexts = Array.isArray(content?.extraText) 
          ? content.extraText.join(' • ') 
          : content?.extraText;
        this._drawText(ctx, extraTexts, pos, layer.style, template.palette);
        break;

      case 'customText':
        const customValue = content?.customFields?.get(layer.id);
        this._drawText(ctx, customValue, pos, layer.style, template.palette);
        break;

      case 'divider':
        this._drawDivider(ctx, pos, layer.style);
        break;

      case 'shape':
        this._drawShape(ctx, pos, layer.style);
        break;

      default:
        console.warn(`Layer type non gestito: ${layer.type}`);
    }
  }

  /**
   * Calcola posizione assoluta da coordinate relative
   */
  _calculatePosition(position, anchor, canvasWidth, canvasHeight) {
    const relX = position.x || 0;
    const relY = position.y || 0;
    const relW = position.w || 1;
    const relH = position.h || 0.1;

    const absW = relW * canvasWidth;
    const absH = relH * canvasHeight;

    let absX = relX * canvasWidth;
    let absY = relY * canvasHeight;

    // Aggiusta per anchor
    switch (anchor) {
      case 'top-center':
        absX -= absW / 2;
        break;
      case 'top-right':
        absX -= absW;
        break;
      case 'center-left':
        absY -= absH / 2;
        break;
      case 'center':
        absX -= absW / 2;
        absY -= absH / 2;
        break;
      case 'center-right':
        absX -= absW;
        absY -= absH / 2;
        break;
      case 'bottom-left':
        absY -= absH;
        break;
      case 'bottom-center':
        absX -= absW / 2;
        absY -= absH;
        break;
      case 'bottom-right':
        absX -= absW;
        absY -= absH;
        break;
      // top-left è default, nessun aggiustamento
    }

    return { x: absX, y: absY, w: absW, h: absH };
  }

  /**
   * Disegna main image
   */
  async _drawMainImage(ctx, asset, pos, style = {}) {
    if (!asset?.url) return;

    try {
      const img = await this._loadImageFromUrl(asset.url);

      ctx.save();

      // Border radius (clip)
      const radius = style.borderRadius || 0;
      if (radius > 0) {
        this._roundRect(ctx, pos.x, pos.y, pos.w, pos.h, radius);
        ctx.clip();
      }

      // Shadow
      if (style.shadow?.enabled) {
        ctx.shadowColor = style.shadow.color || 'rgba(0,0,0,0.5)';
        ctx.shadowBlur = style.shadow.blur || 20;
        ctx.shadowOffsetX = style.shadow.offsetX || 0;
        ctx.shadowOffsetY = style.shadow.offsetY || 10;
      }

      // Calcola dimensioni per object-fit
      const { sx, sy, sw, sh, dx, dy, dw, dh } = this._calculateObjectFit(
        img.width, img.height, pos.w, pos.h, style.objectFit || 'cover'
      );

      ctx.drawImage(img, sx, sy, sw, sh, pos.x + dx, pos.y + dy, dw, dh);

      // Border
      if (style.border?.enabled) {
        ctx.strokeStyle = style.border.color || '#ffffff';
        ctx.lineWidth = style.border.width || 2;
        if (radius > 0) {
          this._roundRect(ctx, pos.x, pos.y, pos.w, pos.h, radius);
        } else {
          ctx.strokeRect(pos.x, pos.y, pos.w, pos.h);
        }
        ctx.stroke();
      }

      ctx.restore();
    } catch (e) {
      console.warn('Main image load failed:', e.message);
    }
  }

  /**
   * Calcola object-fit
   */
  _calculateObjectFit(imgW, imgH, boxW, boxH, fit) {
    let sx = 0, sy = 0, sw = imgW, sh = imgH;
    let dx = 0, dy = 0, dw = boxW, dh = boxH;

    const imgRatio = imgW / imgH;
    const boxRatio = boxW / boxH;

    if (fit === 'cover') {
      if (imgRatio > boxRatio) {
        sw = imgH * boxRatio;
        sx = (imgW - sw) / 2;
      } else {
        sh = imgW / boxRatio;
        sy = (imgH - sh) / 2;
      }
    } else if (fit === 'contain') {
      if (imgRatio > boxRatio) {
        dh = boxW / imgRatio;
        dy = (boxH - dh) / 2;
      } else {
        dw = boxH * imgRatio;
        dx = (boxW - dw) / 2;
      }
    }
    // 'fill' usa valori default

    return { sx, sy, sw, sh, dx, dy, dw, dh };
  }

  /**
   * Disegna testo
   */
  _drawText(ctx, text, pos, style = {}, palette = {}) {
    if (!text) return;

    ctx.save();

    // Font
    const fontWeight = style.fontWeight || 400;
    const fontSize = style.fontSize || 48;
    const fontFamily = style.fontFamily || 'Open Sans';
    ctx.font = `${fontWeight} ${fontSize}px "${fontFamily}"`;

    // Colore
    ctx.fillStyle = style.color || palette.text || '#ffffff';

    // Allineamento
    const align = style.textAlign || 'center';
    ctx.textAlign = align;
    ctx.textBaseline = 'middle';

    // Transform
    let displayText = text;
    if (style.textTransform === 'uppercase') {
      displayText = text.toUpperCase();
    } else if (style.textTransform === 'lowercase') {
      displayText = text.toLowerCase();
    } else if (style.textTransform === 'capitalize') {
      displayText = text.replace(/\b\w/g, c => c.toUpperCase());
    }

    // Calcola X in base ad allineamento
    let textX;
    if (align === 'center') {
      textX = pos.x + pos.w / 2;
    } else if (align === 'right') {
      textX = pos.x + pos.w;
    } else {
      textX = pos.x;
    }

    const textY = pos.y + pos.h / 2;

    // Letter spacing (manuale)
    if (style.letterSpacing && style.letterSpacing > 0) {
      this._drawTextWithSpacing(ctx, displayText, textX, textY, style, pos);
    } else {
      // Shadow
      if (style.shadow?.enabled) {
        ctx.shadowColor = style.shadow.color || 'rgba(0,0,0,0.8)';
        ctx.shadowBlur = style.shadow.blur || 10;
        ctx.shadowOffsetX = style.shadow.offsetX || 2;
        ctx.shadowOffsetY = style.shadow.offsetY || 2;
      }

      // Stroke
      if (style.stroke?.enabled) {
        ctx.strokeStyle = style.stroke.color || 'rgba(0,0,0,0.5)';
        ctx.lineWidth = style.stroke.width || 2;
        ctx.strokeText(displayText, textX, textY);
      }

      // Fill
      ctx.fillText(displayText, textX, textY);
    }

    ctx.restore();
  }

  /**
   * Disegna testo con letter-spacing
   */
  _drawTextWithSpacing(ctx, text, x, y, style, pos) {
    const spacing = style.letterSpacing || 0;
    const chars = text.split('');
    
    // Calcola larghezza totale
    let totalWidth = 0;
    chars.forEach(char => {
      totalWidth += ctx.measureText(char).width + spacing;
    });
    totalWidth -= spacing; // Rimuovi ultimo spacing

    // Calcola startX in base ad allineamento
    let startX;
    if (style.textAlign === 'center') {
      startX = x - totalWidth / 2;
    } else if (style.textAlign === 'right') {
      startX = x - totalWidth;
    } else {
      startX = x;
    }

    // Shadow
    if (style.shadow?.enabled) {
      ctx.shadowColor = style.shadow.color || 'rgba(0,0,0,0.8)';
      ctx.shadowBlur = style.shadow.blur || 10;
      ctx.shadowOffsetX = style.shadow.offsetX || 2;
      ctx.shadowOffsetY = style.shadow.offsetY || 2;
    }

    // Disegna ogni carattere
    ctx.textAlign = 'left';
    let currentX = startX;

    chars.forEach(char => {
      if (style.stroke?.enabled) {
        ctx.strokeStyle = style.stroke.color || 'rgba(0,0,0,0.5)';
        ctx.lineWidth = style.stroke.width || 2;
        ctx.strokeText(char, currentX, y);
      }
      ctx.fillText(char, currentX, y);
      currentX += ctx.measureText(char).width + spacing;
    });
  }

  /**
   * Disegna testo con icona
   */
  _drawTextWithIcon(ctx, text, pos, layer, palette) {
    if (!text) return;

    const icon = layer.icon;
    const style = layer.style || {};

    // Se icona abilitata, disegna simbolo prima del testo
    if (icon?.enabled) {
      ctx.save();

      const iconSize = icon.size || 24;
      const iconColor = icon.color || palette?.accent || '#e74c3c';

      // Disegna simbolo location semplificato
      ctx.fillStyle = iconColor;
      ctx.font = `${iconSize}px Arial`;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      const iconChar = '📍'; // Emoji o usa font icon
      const textWithIcon = `${iconChar} ${text}`;

      // Ora disegna testo normale con icona
      this._drawText(ctx, textWithIcon, pos, style, palette);

      ctx.restore();
    } else {
      this._drawText(ctx, text, pos, style, palette);
    }
  }

  /**
   * Disegna loghi
   */
  async _drawLogos(ctx, logoSlots, logos, canvasWidth, canvasHeight) {
    const slots = logoSlots.slots || [];
    const maxCount = Math.min(logos.length, logoSlots.maxCount || 3, slots.length);

    for (let i = 0; i < maxCount; i++) {
      const logo = logos[i];
      const slot = slots[i];

      if (!logo?.url || !slot) continue;

      try {
        const img = await this._loadImageFromUrl(logo.url);
        const pos = this._calculatePosition(slot.position, slot.anchor, canvasWidth, canvasHeight);

        ctx.save();

        // Opacity
        ctx.globalAlpha = slot.style?.opacity ?? 0.9;

        // Object fit contain per loghi
        const { sx, sy, sw, sh, dx, dy, dw, dh } = this._calculateObjectFit(
          img.width, img.height, pos.w, pos.h, 'contain'
        );

        ctx.drawImage(img, sx, sy, sw, sh, pos.x + dx, pos.y + dy, dw, dh);

        ctx.restore();
      } catch (e) {
        console.warn(`Logo ${i} load failed:`, e.message);
      }
    }
  }

  /**
   * Disegna divider
   */
  _drawDivider(ctx, pos, style = {}) {
    ctx.save();

    ctx.strokeStyle = style.color || '#ffffff';
    ctx.lineWidth = style.width || 2;
    ctx.globalAlpha = style.opacity || 0.5;

    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y + pos.h / 2);
    ctx.lineTo(pos.x + pos.w, pos.y + pos.h / 2);
    ctx.stroke();

    ctx.restore();
  }

  /**
   * Disegna shape
   */
  _drawShape(ctx, pos, style = {}) {
    ctx.save();

    ctx.fillStyle = style.fill || 'rgba(255,255,255,0.1)';
    ctx.strokeStyle = style.stroke || 'transparent';
    ctx.lineWidth = style.strokeWidth || 0;
    ctx.globalAlpha = style.opacity || 1;

    const shape = style.shape || 'rectangle';
    const radius = style.borderRadius || 0;

    if (shape === 'rectangle') {
      if (radius > 0) {
        this._roundRect(ctx, pos.x, pos.y, pos.w, pos.h, radius);
        ctx.fill();
        if (style.strokeWidth) ctx.stroke();
      } else {
        ctx.fillRect(pos.x, pos.y, pos.w, pos.h);
        if (style.strokeWidth) ctx.strokeRect(pos.x, pos.y, pos.w, pos.h);
      }
    } else if (shape === 'circle' || shape === 'ellipse') {
      ctx.beginPath();
      ctx.ellipse(
        pos.x + pos.w / 2,
        pos.y + pos.h / 2,
        pos.w / 2,
        pos.h / 2,
        0, 0, Math.PI * 2
      );
      ctx.fill();
      if (style.strokeWidth) ctx.stroke();
    }

    ctx.restore();
  }

  /**
   * Utility: rounded rectangle
   */
  _roundRect(ctx, x, y, w, h, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + w - radius, y);
    ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
    ctx.lineTo(x + w, y + h - radius);
    ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
    ctx.lineTo(x + radius, y + h);
    ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
  }

  /**
   * Utility: carica immagine da URL o path locale
   */
  async _loadImageFromUrl(url) {
    if (!url) throw new Error('URL mancante');

    // Base64
    if (url.startsWith('data:')) {
      return loadImage(url);
    }

    // Path locale
    if (url.startsWith('/upload') || url.startsWith('./upload')) {
      const localPath = url.startsWith('/') 
        ? path.join(process.cwd(), url)
        : url;
      return loadImage(localPath);
    }

    // URL remoto
    if (url.startsWith('http://') || url.startsWith('https://')) {
      const fetch = require('node-fetch');
      const response = await fetch(url);
      const buffer = await response.buffer();
      return loadImage(buffer);
    }

    // Assume path locale
    return loadImage(url);
  }

  /**
   * Merge layer con override
   */
  _mergeLayerOverride(layer, override) {
    if (!override || Object.keys(override).length === 0) {
      return layer;
    }

    return {
      ...layer,
      position: override.position ? { ...layer.position, ...override.position } : layer.position,
      visible: override.visible !== undefined ? override.visible : layer.visible,
      style: override.style ? { ...layer.style, ...override.style } : layer.style
    };
  }

  /**
   * Quick render (semplificato per quick-generate)
   */
  async quickRender(options) {
    const {
      backgroundUrl,
      content,
      outputPath,
      width = 1080,
      height = 1920
    } = options;

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

    // Background
    if (backgroundUrl) {
      try {
        const img = await this._loadImageFromUrl(backgroundUrl);
        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) {
        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.4, 'rgba(0,0,0,0.2)');
    gradient.addColorStop(0.7, 'rgba(0,0,0,0.6)');
    gradient.addColorStop(1, 'rgba(0,0,0,0.85)');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);

    // Title
    if (content.title) {
      ctx.save();
      ctx.font = 'bold 72px "Montserrat", sans-serif';
      ctx.fillStyle = '#ffffff';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.shadowColor = 'rgba(0,0,0,0.8)';
      ctx.shadowBlur = 15;
      ctx.shadowOffsetY = 4;
      ctx.fillText(content.title.toUpperCase(), width / 2, height * 0.52);
      ctx.restore();
    }

    // Subtitle
    if (content.subtitle) {
      ctx.save();
      ctx.font = '400 32px "Open Sans", sans-serif';
      ctx.fillStyle = '#f0f0f0';
      ctx.textAlign = 'center';
      ctx.shadowColor = 'rgba(0,0,0,0.6)';
      ctx.shadowBlur = 8;
      ctx.fillText(content.subtitle, width / 2, height * 0.60);
      ctx.restore();
    }

    // Date
    if (content.eventDate) {
      ctx.save();
      ctx.font = '400 48px "Bebas Neue", sans-serif';
      ctx.fillStyle = '#ffd700';
      ctx.textAlign = 'center';
      ctx.shadowColor = 'rgba(0,0,0,0.8)';
      ctx.shadowBlur = 10;
      const dateText = content.eventTime 
        ? `${content.eventDate} • ORE ${content.eventTime}`
        : content.eventDate;
      ctx.fillText(dateText.toUpperCase(), width / 2, height * 0.70);
      ctx.restore();
    }

    // Location
    if (content.location) {
      ctx.save();
      ctx.font = '600 28px "Open Sans", sans-serif';
      ctx.fillStyle = '#ffffff';
      ctx.textAlign = 'center';
      ctx.fillText(`📍 ${content.location}`, width / 2, height * 0.78);
      ctx.restore();
    }

    // Contacts
    if (content.contacts) {
      ctx.save();
      ctx.font = '400 22px "Open Sans", sans-serif';
      ctx.fillStyle = '#cccccc';
      ctx.textAlign = 'center';
      ctx.fillText(content.contacts, width / 2, height * 0.86);
      ctx.restore();
    }

    // Salva
    const buffer = canvas.toBuffer('image/png');
    await fs.writeFile(outputPath, buffer);

    return {
      path: outputPath,
      size: buffer.length,
      dimensions: { width, height }
    };
  }
}

module.exports = new PosterRenderer();