"use client";

import { useRef } from "react";
import { useReducedMotionSafe } from "@/components/motion/use-reduced-motion-safe";
import { useBrushReveal } from "./useBrushReveal";

interface BrushRevealImageProps {
  /** "before" — the real image, always visible underneath (also the accessible/SEO <img>). */
  beforeSrc: string;
  /** "after" — a separately-prepared treated image (e.g. blurred) shown on top; swap this file to change the look, no code change needed. */
  afterSrc: string;
  alt: string;
  /** Applied to the outer container — pass the same positioning classes the plain <img> used to have. */
  className?: string;
}

/**
 * Interactive "ink brush reveal" between two prepared images. The "before"
 * <img> stays in the DOM as the accessible/SEO content; a decorative
 * <canvas> overlay redraws the "after" image each frame and wipes it away
 * along the pointer/touch trail, revealing "before" underneath. Falls back
 * to a plain <img> (no canvas, no animation) when the user prefers reduced
 * motion; if canvas 2D somehow isn't supported, `useBrushReveal`'s effect
 * no-ops and the untouched "before" <img> underneath is what's visible
 * either way — the thumbnail never disappears.
 */
export function BrushRevealImage({ beforeSrc, afterSrc, alt, className }: BrushRevealImageProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const topImageRef = useRef<HTMLImageElement>(null);
  const enabled = !useReducedMotionSafe();

  useBrushReveal({ containerRef, canvasRef, topImageRef, enabled });

  return (
    <div ref={containerRef} className={className}>
      {/* eslint-disable-next-line @next/next/no-img-element -- static brand asset, drawn onto <canvas> too */}
      <img src={beforeSrc} alt={alt} className="absolute inset-0 h-full w-full object-cover" />
      {enabled && (
        <>
          {/* Source for the canvas draw only — never shown directly, so no alt text needed. */}
          {/* eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text -- decorative canvas source image, not rendered visually */}
          <img ref={topImageRef} src={afterSrc} aria-hidden="true" className="hidden" />
          <canvas ref={canvasRef} aria-hidden="true" className="pointer-events-none absolute inset-0 h-full w-full" />
        </>
      )}
    </div>
  );
}
