/**
 * Shared video card HTML generators for GrapesJS, MkDocs, and email templates.
 * Produces static HTML that works without JavaScript.
 */

export interface VideoCardData {
  id: number | string;
  title: string;
  durationSeconds: number;
  quality: string;
  viewCount: number;
  thumbnailUrl: string;
}

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

export function formatDuration(seconds: number): string {
  if (!seconds || seconds <= 0) return '0:00';
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);
  if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  return `${m}:${String(s).padStart(2, '0')}`;
}

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 video card HTML for GrapesJS landing pages and MkDocs.
 * Dark theme, inline styles, entire card is a clickable link.
 */
export function generateVideoCardHtml(video: VideoCardData, options: VideoCardOptions = {}): string {
  const { baseUrl } = options;
  const watchUrl = resolveUrl(`/gallery?expanded=${video.id}`, baseUrl);
  const thumbUrl = resolveUrl(video.thumbnailUrl, baseUrl);
  const title = escapeHtml(video.title || 'Untitled Video');
  const duration = formatDuration(video.durationSeconds);
  const views = formatViewCount(video.viewCount);
  const quality = escapeHtml(video.quality || '');

  return `<div class="video-card-block" data-video-id="${video.id}" data-video-title="${escapeHtml(video.title)}" data-video-duration="${video.durationSeconds}" data-video-quality="${escapeHtml(video.quality || '')}" data-video-views="${video.viewCount}" style="max-width: 480px; margin: 0 auto;">
  <a href="${watchUrl}" 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: 56.25%; background: #0d1b2a; overflow: hidden;">
      <img src="${thumbUrl}" alt="${title}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;" />
      ${quality ? `<span style="position: absolute; top: 8px; left: 8px; background: #9d4edd; color: #fff; font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 4px;">${quality}</span>` : ''}
      <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;">${duration}</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="28" height="28" viewBox="0 0 24 24" fill="#fff" style="margin-left: 3px;"><polygon points="5,3 19,12 5,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>
      <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: #9d4edd; font-size: 13px; font-weight: 500;">Watch &rarr;</span>
      </div>
    </div>
  </a>
</div>`;
}

/**
 * Table-based video card HTML for email templates.
 * Uses inline styles and table layout for maximum email client compatibility.
 */
export function generateVideoCardEmailHtml(video: VideoCardData, options: VideoCardOptions = {}): string {
  const { baseUrl } = options;
  const watchUrl = resolveUrl(`/gallery?expanded=${video.id}`, baseUrl);
  const thumbUrl = resolveUrl(video.thumbnailUrl, baseUrl);
  const title = escapeHtml(video.title || 'Untitled Video');
  const duration = formatDuration(video.durationSeconds);
  const views = formatViewCount(video.viewCount);
  const quality = escapeHtml(video.quality || '');

  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="${watchUrl}" 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;">
                  ${duration}${quality ? ` &bull; ${quality}` : ''} &bull; ${views}
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td style="padding-top: 12px; text-align: center;">
            <a href="${watchUrl}" style="display: inline-block; padding: 10px 24px; background-color: #9d4edd; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
              &#9654; Watch Video
            </a>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>`;
}

/**
 * Plain text fallback for email text part.
 */
export function generateVideoCardPlainText(video: VideoCardData, options: VideoCardOptions = {}): string {
  const { baseUrl } = options;
  const watchUrl = resolveUrl(`/gallery?expanded=${video.id}`, baseUrl);
  const duration = formatDuration(video.durationSeconds);
  const views = formatViewCount(video.viewCount);
  const quality = video.quality || '';
  const meta = [duration, quality, views].filter(Boolean).join(', ');

  return `Watch "${video.title}" (${meta}) - ${watchUrl}`;
}
