export type PreviewKind = 'image' | 'video' | 'markdown' | 'code' | 'diff' | 'document' | 'pdf' | 'file';

function isPreviewRouteUrl(url: string) {
  if (typeof window === 'undefined') {
    return false;
  }

  try {
    const parsed = new URL(url, window.location.origin);
    const pathname = parsed.pathname.toLowerCase();
    const hasKnownFileExtension = /\.[a-z0-9]+$/i.test(pathname);
    return parsed.origin === window.location.origin && !hasKnownFileExtension && /^https?:$/.test(parsed.protocol);
  } catch {
    return false;
  }
}

function hasImageFormatSearchParam(url: URL) {
  const imageFormatPattern = /^(?:png|jpe?g|gif|webp|svg|bmp|ico|avif)$/i;
  const candidateKeys = ['fm', 'format', 'ext', 'output-format'];

  return candidateKeys.some((key) => {
    const value = url.searchParams.get(key)?.trim() ?? '';
    return imageFormatPattern.test(value);
  });
}

function isLikelyRemoteImageUrl(url: string) {
  try {
    const parsed = new URL(url, typeof window !== 'undefined' ? window.location.origin : 'https://local.invalid');

    if (!/^https?:$/i.test(parsed.protocol)) {
      return false;
    }

    const pathname = parsed.pathname.toLowerCase();

    if (/\.(html?|php|aspx?)$/i.test(pathname)) {
      return false;
    }

    if (hasImageFormatSearchParam(parsed)) {
      return true;
    }

    const hostname = parsed.hostname.toLowerCase();
    const isImageCdnHost =
      hostname.startsWith('images.') ||
      hostname.startsWith('img.') ||
      hostname.includes('unsplash.com') ||
      hostname.includes('pexels.com') ||
      hostname.includes('pixabay.com') ||
      hostname.includes('googleusercontent.com') ||
      hostname.includes('imgur.com');

    if (isImageCdnHost) {
      return true;
    }

    const hasImageSizingParams = ['w', 'width', 'h', 'height', 'fit', 'crop', 'q', 'auto', 'dpr'].some((key) =>
      parsed.searchParams.has(key),
    );
    const hasImageLikePath = /(image|images|photo|photos|img|media)/i.test(`${hostname}${pathname}`);

    return hasImageSizingParams && hasImageLikePath;
  } catch {
    return false;
  }
}

export function classifyPreviewKind(url: string): PreviewKind {
  const pathname = url.toLowerCase().split('?')[0] ?? '';

  if (/\.(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(pathname)) {
    return 'image';
  }

  if (/\.(mp4|webm|mov|m4v|ogg)$/i.test(pathname)) {
    return 'video';
  }

  if (/\.(md|markdown)$/i.test(pathname)) {
    return 'markdown';
  }

  if (/\.(diff|patch)$/i.test(pathname)) {
    return 'diff';
  }

  if (/\.(ts|tsx|js|jsx|json|css|scss|html|xml|java|kt|sql|sh|py|go|rs|c|cpp|h|hpp|yml|yaml)$/i.test(pathname)) {
    return 'code';
  }

  if (/\.(txt|log|csv)$/i.test(pathname)) {
    return 'document';
  }

  if (/\.pdf$/i.test(pathname)) {
    return 'pdf';
  }

  if (isLikelyRemoteImageUrl(url)) {
    return 'image';
  }

  if (isPreviewRouteUrl(url)) {
    return 'document';
  }

  return 'file';
}
