/**
 * Shared photo card HTML generators for GrapesJS, MkDocs, and email templates.
 * Produces static HTML that works without JavaScript.
 * Mirrors videoCardHtml.ts with photo-specific fields and green/blue theme.
 */

export interface PhotoCardData {
  id: number | string;
  title: string;
  description?: string;
  showMetadata: boolean;
  thumbnailUrl: string;
  format?: string;
  width?: number;
  height?: number;
  viewCount: number;
}

export interface PhotoCardOptions {
  baseUrl?: string; // For absolute URL generation (email/MkDocs)
}

export function formatDimensions(width?: number, height?: number): string {
  if (!width || !height) return '';
  return `${width}\u00D7${height}`;
}

export function formatViewCount(count: number): string {
  if (!count || count <= 0) return '0 views';
  if (count === 1) return '1 view';
  if (count < 1000) return `${count} views`;
  if (count < 1_000_000) return `${(count / 1000).toFixed(1).replace(/\.0$/, '')}K views`;
  return `${(count / 1_000_000).toFixed(1).replace(/\.0$/, '')}M views`;
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

function resolveUrl(path: string, baseUrl?: string): string {
  if (!baseUrl) return path;
  return `${baseUrl.replace(/\/$/, '')}${path}`;
}

/**
 * CSS-based photo card HTML for GrapesJS landing pages and MkDocs.
 * Dark theme, inline styles, entire card is a clickable link.
 */
export function generatePhotoCardHtml(photo: PhotoCardData, options: PhotoCardOptions = {}): string {
  const { baseUrl } = options;
  const galleryUrl = resolveUrl(`/gallery?expanded=photo-${photo.id}`, baseUrl);
  const thumbUrl = resolveUrl(photo.thumbnailUrl, baseUrl);
  const title = escapeHtml(photo.title || 'Untitled Photo');
  const description = photo.description ? escapeHtml(photo.description) : '';
  const views = formatViewCount(photo.viewCount);
  const format = photo.format ? escapeHtml(photo.format.toUpperCase()) : '';
  const dimensions = formatDimensions(photo.width, photo.height);

  return `<div class="photo-card-block" data-photo-id="${photo.id}" data-photo-title="${escapeHtml(photo.title)}" data-photo-format="${escapeHtml(photo.format || '')}" data-photo-width="${photo.width || ''}" data-photo-height="${photo.height || ''}" data-photo-views="${photo.viewCount}" style="max-width: 480px; margin: 0 auto;">
  <a href="${galleryUrl}" style="display: block; text-decoration: none; color: inherit; border-radius: 12px; overflow: hidden; background: #1b2838; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">
    <div style="position: relative; padding-bottom: 66.67%; background: #0d1b2a; overflow: hidden;">
      <img src="${thumbUrl}" alt="${title}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;" />
      ${format ? `<span style="position: absolute; top: 8px; left: 8px; background: #2e7d32; color: #fff; font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 4px;">${format}</span>` : ''}
      ${dimensions ? `<span style="position: absolute; bottom: 8px; right: 8px; background: rgba(0,0,0,0.8); color: #fff; font-size: 12px; font-weight: 500; padding: 2px 6px; border-radius: 4px;">${dimensions}</span>` : ''}
      <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 56px; height: 56px; background: rgba(0,0,0,0.5); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>
      </div>
    </div>
    <div style="padding: 12px 16px;">
      <div style="color: #fff; font-size: 15px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${title}</div>
      ${description ? `<div style="color: #aabbcc; font-size: 13px; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${description}</div>` : ''}
      <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 6px;">
        <span style="color: #8899aa; font-size: 13px;">${views}</span>
        <span style="color: #43cea2; font-size: 13px; font-weight: 500;">View &rarr;</span>
      </div>
    </div>
  </a>
</div>`;
}

/**
 * Table-based photo card HTML for email templates.
 * Uses inline styles and table layout for maximum email client compatibility.
 */
export function generatePhotoCardEmailHtml(photo: PhotoCardData, options: PhotoCardOptions = {}): string {
  const { baseUrl } = options;
  const galleryUrl = resolveUrl(`/gallery?expanded=photo-${photo.id}`, baseUrl);
  const thumbUrl = resolveUrl(photo.thumbnailUrl, baseUrl);
  const title = escapeHtml(photo.title || 'Untitled Photo');
  const views = formatViewCount(photo.viewCount);
  const format = photo.format ? escapeHtml(photo.format.toUpperCase()) : '';
  const dimensions = formatDimensions(photo.width, photo.height);

  return `<table cellpadding="0" cellspacing="0" border="0" style="max-width: 480px; margin: 16px auto; border-radius: 8px; overflow: hidden; background-color: #1b2838;">
  <tr>
    <td style="padding: 0;">
      <a href="${galleryUrl}" style="display: block; text-decoration: none;">
        <img src="${thumbUrl}" alt="${title}" width="480" style="width: 100%; max-width: 480px; height: auto; display: block;" />
      </a>
    </td>
  </tr>
  <tr>
    <td style="padding: 12px 16px;">
      <table cellpadding="0" cellspacing="0" border="0" width="100%">
        <tr>
          <td style="color: #ffffff; font-size: 15px; font-weight: 600; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            ${title}
          </td>
        </tr>
        <tr>
          <td style="padding-top: 6px;">
            <table cellpadding="0" cellspacing="0" border="0" width="100%">
              <tr>
                <td style="color: #8899aa; font-size: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                  ${format ? `${format} &bull; ` : ''}${dimensions ? `${dimensions} &bull; ` : ''}${views}
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td style="padding-top: 12px; text-align: center;">
            <a href="${galleryUrl}" style="display: inline-block; padding: 10px 24px; background-color: #43cea2; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
              &#128247; View Photo
            </a>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>`;
}

/**
 * Plain text fallback for email text part.
 */
export function generatePhotoCardPlainText(photo: PhotoCardData, options: PhotoCardOptions = {}): string {
  const { baseUrl } = options;
  const galleryUrl = resolveUrl(`/gallery?expanded=photo-${photo.id}`, baseUrl);
  const views = formatViewCount(photo.viewCount);
  const format = photo.format?.toUpperCase() || '';
  const dimensions = formatDimensions(photo.width, photo.height);
  const meta = [format, dimensions, views].filter(Boolean).join(', ');

  return `View "${photo.title}" (${meta}) - ${galleryUrl}`;
}
