/**
 * Screenshot Service
 * Generates banner preview screenshots.
 * Primary: Puppeteer (if available)
 * Fallback: Rendered HTML preview image
 */

export interface ScreenshotResult {
  success: boolean;
  screenshotUrl?: string;
  fallback?: boolean;
  error?: string;
}

/**
 * Generate a preview screenshot of a banner in context.
 * Falls back to an HTML preview page URL if Puppeteer is unavailable.
 */
export async function generateBannerPreview(params: {
  bannerUrl: string;
  destinationUrl: string;
  width: number;
  height: number;
  publicationName: string;
  campaignId: string;
}): Promise<ScreenshotResult> {
  // Try Puppeteer first
  try {
    const puppeteer = await import('puppeteer').catch(() => null);
    if (puppeteer) {
      const browser = await puppeteer.default.launch({
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox'],
      });
      const page = await browser.newPage();
      await page.setViewport({ width: 1440, height: 900 });

      // Build a preview HTML page
      const previewHtml = buildPreviewHtml(params);
      await page.setContent(previewHtml, { waitUntil: 'networkidle0' });

      const screenshotBuffer = await page.screenshot({ type: 'png', fullPage: false });
      await browser.close();

      // In production, upload to Supabase storage
      // For now return a data URL indicator
      return {
        success: true,
        screenshotUrl: `data:image/png;base64,${Buffer.from(screenshotBuffer).toString('base64')}`,
        fallback: false,
      };
    }
  } catch {
    // Puppeteer not available — use fallback
  }

  // Fallback: return a preview page URL
  const previewUrl = `/api/adops/preview?campaignId=${params.campaignId}&bannerUrl=${encodeURIComponent(params.bannerUrl)}&w=${params.width}&h=${params.height}`;
  return {
    success: true,
    screenshotUrl: previewUrl,
    fallback: true,
  };
}

function buildPreviewHtml(params: {
  bannerUrl: string;
  destinationUrl: string;
  width: number;
  height: number;
  publicationName: string;
}): string {
  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: Arial, sans-serif; background: #f0f0f0; margin: 0; padding: 20px; }
    .site-header { background: #1a1a2e; color: white; padding: 16px 24px; margin-bottom: 20px; font-size: 20px; font-weight: bold; }
    .content-area { max-width: 1200px; margin: 0 auto; display: flex; gap: 20px; }
    .main-content { flex: 1; background: white; padding: 20px; min-height: 400px; }
    .ad-container { border: 3px solid #e74c3c; padding: 4px; display: inline-block; position: relative; }
    .ad-label { position: absolute; top: -20px; left: 0; background: #e74c3c; color: white; font-size: 11px; padding: 2px 6px; }
    .article-placeholder { background: #eee; height: 200px; margin-bottom: 16px; display: flex; align-items: center; justify-content: center; color: #999; }
    h2 { color: #333; margin-bottom: 16px; }
  </style>
</head>
<body>
  <div class="site-header">${params.publicationName}</div>
  <div class="content-area">
    <div class="main-content">
      <div style="text-align: center; margin-bottom: 20px;">
        <div class="ad-container">
          <div class="ad-label">AD PREVIEW</div>
          <a href="${params.destinationUrl}" target="_blank">
            <img src="${params.bannerUrl}" width="${params.width}" height="${params.height}" alt="Banner Ad Preview" style="display: block;">
          </a>
        </div>
      </div>
      <h2>Sample Article Headline</h2>
      <div class="article-placeholder">Article content area</div>
    </div>
  </div>
</body>
</html>`;
}
