// src/utils/normalizeSvg.ts
// Ensures every incoming SVG string has a viewBox and scales correctly.

export function normalizeSvg(svgRaw: string): string {
  if (!svgRaw) return svgRaw;

  // Quick sanity: trim and ensure it's an SVG string
  const trimmed = svgRaw.trim();
  if (!trimmed.startsWith("<svg")) return trimmed;

  // Parse attributes safely
  const openTagEnd = trimmed.indexOf(">");
  if (openTagEnd === -1) return trimmed;

  const openTag = trimmed.slice(0, openTagEnd + 1);
  const rest = trimmed.slice(openTagEnd + 1);

  // If there is already a viewBox, just ensure preserveAspectRatio
  const hasViewBox = /viewBox\s*=\s*['"][^'"]+['"]/i.test(openTag);

  // Extract width/height if present (could be like "512", "512px", "100%" etc.)
  const widthMatch = openTag.match(/\bwidth\s*=\s*['"]([^'"]+)['"]/i);
  const heightMatch = openTag.match(/\bheight\s*=\s*['"]([^'"]+)['"]/i);

  const widthVal = widthMatch?.[1] ?? "";
  const heightVal = heightMatch?.[1] ?? "";

  const numeric = (v: string) => {
    const n = parseFloat(v.replace(/px|pt|em|rem|%/g, ""));
    return Number.isFinite(n) && n > 0 ? n : undefined;
  };

  let w = numeric(widthVal);
  let h = numeric(heightVal);

  // Fallback square if neither width nor height can be parsed.
  if (!w && h) w = h;
  if (!h && w) h = w;
  if (!w && !h) {
    // Try to infer from common defaults; 512 is a sensible safety default
    w = 512; h = 512;
  }

  // Ensure preserveAspectRatio="xMidYMid meet"
  let newOpenTag = openTag;
  if (!/preserveAspectRatio=/i.test(newOpenTag)) {
    newOpenTag = newOpenTag.replace(
      /^<svg/i,
      `<svg preserveAspectRatio="xMidYMid meet"`
    );
  } else {
    newOpenTag = newOpenTag.replace(
      /preserveAspectRatio\s*=\s*['"][^'"]+['"]/i,
      `preserveAspectRatio="xMidYMid meet"`
    );
  }

  if (!hasViewBox) {
    newOpenTag = newOpenTag.replace(
      /^<svg/i,
      `<svg viewBox="0 0 ${w} ${h}"`
    );
  }

  // Remove explicit width/height so the SVG can flex to container
  newOpenTag = newOpenTag
    .replace(/\bwidth\s*=\s*['"][^'"]+['"]/gi, "")
    .replace(/\bheight\s*=\s*['"][^'"]+['"]/gi, "");

  return `${newOpenTag}${rest}`;
}
