export interface ViewportDetectionResult {
  hasViewportMeta: boolean;
  viewportContent: string | null;
  isOptimal: boolean;
  issues: string[];
}

export function detectViewportConfiguration(domHtml: string): ViewportDetectionResult {
  const viewportMatch =
    domHtml.match(/<meta[^>]+name=["']viewport["'][^>]*>/i) ??
    domHtml.match(/<meta[^>]+content=["'][^"']*["'][^>]+name=["']viewport["'][^>]*>/i);

  if (!viewportMatch) {
    return {
      hasViewportMeta: false,
      viewportContent: null,
      isOptimal: false,
      issues: ["Missing viewport meta tag -- mobile browsers will render at desktop width"],
    };
  }

  const contentMatch = viewportMatch[0].match(/content=["']([^"']*)["']/i);
  const content = contentMatch?.[1] ?? null;

  if (!content) {
    return {
      hasViewportMeta: true,
      viewportContent: null,
      isOptimal: false,
      issues: ["Viewport meta tag has no content attribute"],
    };
  }

  const hasDeviceWidth = /width\s*=\s*device-width/i.test(content);
  const hasInitialScale = /initial-scale\s*=\s*1/i.test(content);
  const hasUserScalableNo = /user-scalable\s*=\s*no/i.test(content);
  const hasMaxScale1 = /maximum-scale\s*=\s*1(?:[^.]|$)/i.test(content);

  const issues: string[] = [];
  if (!hasDeviceWidth) issues.push("Viewport does not set width=device-width");
  if (!hasInitialScale) issues.push("Viewport does not set initial-scale=1");
  if (hasUserScalableNo) issues.push("user-scalable=no prevents accessibility zoom");
  if (hasMaxScale1) issues.push("maximum-scale=1 prevents pinch-to-zoom on iOS");

  const isOptimal = hasDeviceWidth && hasInitialScale && !hasUserScalableNo;

  return { hasViewportMeta: true, viewportContent: content, isOptimal, issues };
}
