// PaintingArt, wraps ColoringArt and animates a "brush" filling it with color over time.
// The strategy: render the same SVG twice, once as black-stroke linework (top), once as
// a colored, filled version (bottom). A clip-path sweeps across the colored version, revealing
// it stroke by stroke. A small brush tip rides along the sweep front.

const PAINT_SEQUENCES = {
  // Each entry: a list of {color, fromY, toY}, but we'll keep it simple with one sweep
  // and rely on multi-color radial regions for visual interest.
  default: [
    { color: '#FFD7A8' }, // skin/cream
    { color: '#FFC857' }, // sun
    { color: '#FF8A7A' }, // coral
    { color: '#A8D5F2' }, // sky
    { color: '#BFE7C9' }, // mint
    { color: '#D8C7F0' }, // lilac
  ],
};

// Color zones per art so each painting feels intentional
const PAINT_FILLS = {
  unicorn:  ['#FFE7A1','#FFB3D9','#A8D5F2','#D8C7F0','#FFC857'],
  dino:     ['#BFE7C9','#9ED6B0','#FFE7A1','#FF8A7A'],
  cat:      ['#FFD7A8','#FFB088','#FFE7A1','#A8D5F2'],
  santa:    ['#FF8A7A','#FFE7A1','#A8D5F2','#FFD7A8'],
  soccer:   ['#FFE7A1','#A8D5F2','#FF8A7A','#BFE7C9'],
  princess: ['#FFB3D9','#D8C7F0','#FFE7A1','#A8D5F2'],
  tractor:  ['#FF8A7A','#F5C544','#A8D5F2','#BFE7C9'],
  bunny:    ['#FFE7A1','#FFD7A8','#FFB3D9','#A8D5F2'],
  rocket:   ['#FF8A7A','#A8D5F2','#FFE7A1','#D8C7F0'],
  mandala:  ['#FF8A7A','#FFE7A1','#A8D5F2','#BFE7C9','#D8C7F0','#FFB3D9'],
  kite:     ['#FF8A7A','#FFE7A1','#A8D5F2','#D8C7F0'],
  owl:      ['#FFD7A8','#F5C544','#FF8A7A','#A8D5F2'],
};

const PaintingArt = ({ artKey, className = "", duration = 4200, loop = true, paused = false, autoStart = true }) => {
  const [progress, setProgress] = React.useState(0); // 0..1
  const [phase, setPhase] = React.useState('idle');  // 'idle'|'painting'|'done'
  const rafRef = React.useRef(null);
  const startRef = React.useRef(null);

  React.useEffect(() => {
    if (!autoStart || paused) return;
    let cancelled = false;
    const start = (delay = 0) => {
      setTimeout(() => {
        if (cancelled) return;
        startRef.current = performance.now();
        setPhase('painting');
        const tick = (now) => {
          if (cancelled) return;
          const t = Math.min(1, (now - startRef.current) / duration);
          setProgress(t);
          if (t < 1) {
            rafRef.current = requestAnimationFrame(tick);
          } else {
            setPhase('done');
            if (loop) {
              setTimeout(() => {
                if (cancelled) return;
                setProgress(0);
                setPhase('idle');
                start(400);
              }, 1600);
            }
          }
        };
        rafRef.current = requestAnimationFrame(tick);
      }, delay);
    };
    start(300);
    return () => {
      cancelled = true;
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
  }, [artKey, duration, loop, paused, autoStart]);

  const fills = PAINT_FILLS[artKey] || PAINT_FILLS.unicorn;

  return (
    <div className={cls("relative", className)}>
      {/* BASE: black linework, always visible */}
      <ColoringArt artKey={artKey} className="absolute inset-0 w-full h-full"/>

      {/* PAINT: same art, but each stroke filled with a color from the palette,
          revealed by a sweeping clip-path (top → bottom) */}
      <div className="absolute inset-0 overflow-hidden"
           style={{ clipPath: `inset(0 0 ${(1 - progress) * 100}% 0)` }}>
        <PaintFillArt artKey={artKey} fills={fills}/>
      </div>

      {/* BRUSH TIP, rides on the wet edge */}
      {phase === 'painting' && (
        <div className="absolute left-0 right-0 pointer-events-none"
             style={{ top: `calc(${progress * 100}% - 18px)` }}>
          <BrushTip x={Math.sin(progress * Math.PI * 4) * 30}/>
        </div>
      )}

      {/* SPARKLES on completion */}
      {phase === 'done' && loop && (
        <div className="absolute inset-0 pointer-events-none">
          <span className="absolute top-[15%] left-[20%] text-xl twinkle" style={{animationDelay:'0s'}}>✨</span>
          <span className="absolute top-[35%] right-[18%] text-lg twinkle" style={{animationDelay:'0.3s'}}>✨</span>
          <span className="absolute bottom-[20%] left-[35%] text-base twinkle" style={{animationDelay:'0.6s'}}>⭐</span>
        </div>
      )}
    </div>
  );
};

// PaintFillArt: re-renders ColoringArt with a CSS rule that fills strokes with palette colors.
// Simple approach: we wrap and apply a CSS filter to make strokes appear painted.
const PaintFillArt = ({ artKey, fills }) => {
  // Build a unique CSS class so multiple instances don't collide
  const id = React.useId().replace(/:/g, '');
  const css = `
    .paint-${id} svg { stroke: #1F2A44; }
    .paint-${id} svg circle, .paint-${id} svg ellipse, .paint-${id} svg rect {
      fill: ${fills[0]};
    }
    .paint-${id} svg path:nth-of-type(2n)   { fill: ${fills[1] || fills[0]}; fill-opacity: 0.85; }
    .paint-${id} svg path:nth-of-type(3n)   { fill: ${fills[2] || fills[0]}; fill-opacity: 0.85; }
    .paint-${id} svg path:nth-of-type(5n)   { fill: ${fills[3] || fills[0]}; fill-opacity: 0.85; }
    .paint-${id} svg path:nth-of-type(7n+1) { fill: ${fills[4] || fills[1] || fills[0]}; fill-opacity: 0.85; }
    .paint-${id} svg circle:nth-of-type(2n) { fill: ${fills[2] || fills[1] || fills[0]}; }
    .paint-${id} svg circle:nth-of-type(3n) { fill: ${fills[3] || fills[1] || fills[0]}; }
  `;
  return (
    <>
      <style>{css}</style>
      <div className={`paint-${id} w-full h-full`}>
        <ColoringArt artKey={artKey} className="w-full h-full"/>
      </div>
    </>
  );
};

const BrushTip = ({ x = 0 }) => (
  <div className="absolute left-1/2 -translate-x-1/2 transition-transform duration-300"
       style={{ transform: `translate(calc(-50% + ${x}px), 0) rotate(-30deg)` }}>
    <svg width="40" height="48" viewBox="0 0 40 48" className="drop-shadow-md">
      {/* handle */}
      <rect x="17" y="2" width="6" height="22" rx="2" fill="#7B4F2A"/>
      <rect x="17" y="22" width="6" height="6" fill="#C8A06B"/>
      {/* ferrule */}
      <rect x="14" y="26" width="12" height="6" rx="1" fill="#B0B7C2"/>
      {/* bristles + paint blob */}
      <path d="M14 32 L26 32 L24 44 Q20 48 16 44 Z" fill="#FF8A7A"/>
      <ellipse cx="20" cy="46" rx="6" ry="2" fill="#FF8A7A" opacity="0.6"/>
    </svg>
  </div>
);

Object.assign(window, { PaintingArt });
