"use client";

import { useInView, useReducedMotion } from "motion/react";
import { useRef, type CSSProperties, type ReactNode } from "react";
import { cn } from "@/lib/utils";

type ChartFrameProps = {
  /** viewBox coordinate space (drawing units, not px). */
  width: number;
  height: number;
  /** a11y description. */
  label?: string;
  className?: string;
  style?: CSSProperties;
  /** useInView amount threshold. Default 0.4. */
  amount?: number;
  /** Render-prop: receives the in-view + reduced-motion flags for the SVG body. */
  children: (ctx: { inView: boolean; reduce: boolean }) => ReactNode;
};

/**
 * ChartFrame — responsive SVG wrapper shared by every sd chart/diagram.
 *
 * Scales to its container width (viewBox + width 100%), fires once on viewport
 * entry, and forwards `{ inView, reduce }` so each chart can drive its own
 * motion/react animation and degrade to the final state under reduced motion.
 * See sd DATAVIZ.md.
 */
export function ChartFrame({
  width,
  height,
  label,
  className,
  style,
  amount = 0.4,
  children,
}: ChartFrameProps) {
  const ref = useRef<SVGSVGElement>(null);
  const inView = useInView(ref, { once: true, amount });
  const reduce = useReducedMotion() ?? false;

  return (
    <svg
      ref={ref}
      viewBox={`0 0 ${width} ${height}`}
      width="100%"
      role="img"
      aria-label={label}
      preserveAspectRatio="xMidYMid meet"
      className={cn(className)}
      style={{ display: "block", width: "100%", height: "auto", ...style }}
    >
      {children({ inView, reduce })}
    </svg>
  );
}
