import type { TraceMetadata } from '../types/engine';

interface SvgPreviewProps {
  svgOutput: string | null;
  isLoading: boolean;
  error: string | null;
  metadata: TraceMetadata | null;
}

/**
 * Strip width/height attributes from an SVG string while keeping viewBox
 * for responsive scaling.
 */
function makeResponsiveSvg(svg: string): string {
  return svg
    .replace(/\s+width="[^"]*"/g, '')
    .replace(/\s+height="[^"]*"/g, '')
    .replace(/\s+width='[^']*'/g, '')
    .replace(/\s+height='[^']*'/g, '');
}

export default function SvgPreview({
  svgOutput,
  isLoading,
  error,
  metadata,
}: SvgPreviewProps) {
  if (error) {
    return (
      <div className="svg-preview svg-preview--error">
        <p className="svg-preview-error">⚠ {error}</p>
        <p className="svg-preview-hint">
          Try adjusting parameters or selecting a different preset
        </p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="svg-preview svg-preview--loading">
        <div className="svg-preview-spinner" />
        <p className="svg-preview-status">Vectorizing…</p>
      </div>
    );
  }

  if (!svgOutput) {
    return (
      <div className="svg-preview svg-preview--empty">
        <p className="svg-preview-placeholder">
          Upload an image to begin vectorization
        </p>
      </div>
    );
  }

  const responsiveSvg = makeResponsiveSvg(svgOutput);

  return (
    <div className="svg-preview svg-preview--ready">
      <div
        className="svg-preview-container"
        dangerouslySetInnerHTML={{ __html: responsiveSvg }}
      />
      {metadata && (
        <div className="svg-preview-meta">
          <span>
            {metadata.path_count} paths · {metadata.node_count_total} nodes
          </span>
          <span>{metadata.processing_ms}ms</span>
          {metadata.warnings.length > 0 && (
            <span className="svg-preview-warnings">
              ⚠ {metadata.warnings.join(', ')}
            </span>
          )}
        </div>
      )}
    </div>
  );
}
