// StClementsSketch.jsx — renders ink line-work + 4 named colour washes.
// Reads window.SKETCH_PATHS and window.SKETCH_COLOUR from sketch-data.js.
//
// Rendering goals:
//   - Sketch lines look hand-drawn: per-stroke duration scales with length,
//     small jitter on start times, soft ease per stroke.
//   - Watercolour shapes (tree canopy, distant dome, terracotta pot, pink
//     flowers) bloom in sequentially after the ink finishes drawing.

const StClementsSketch = ({
  play = false,
  durationMs = 7000,
  color = "rgba(20,20,20,0.85)",
  strokeWidth = 1.6,
  showColour = true,
  colourFadeMs = 1400,
  colourStaggerMs = 380,
}) => {
  const sketchPaths = window.SKETCH_PATHS || [];
  const colourShapes = window.SKETCH_COLOUR || [];
  const N = sketchPaths.length || 1;

  const svgRef = React.useRef(null);
  const colourGroupRef = React.useRef(null);

  // Once the sketch has (mostly) finished drawing, fade the colour washes in
  // one after the other. Order is the same as in the source SVG: tree canopy,
  // distant dome, terracotta pot, pink flowers.
  React.useEffect(() => {
    if (!colourGroupRef.current) return;
    const els = colourGroupRef.current.querySelectorAll("path");
    els.forEach((el) => {
      el.style.opacity = 0;
      el.style.transition = `opacity ${colourFadeMs}ms cubic-bezier(.22,.9,.32,1)`;
    });
    if (!play) return;
    const startAt = durationMs + 250;
    const timeouts = [];
    els.forEach((el, i) => {
      timeouts.push(
        setTimeout(() => {
          el.style.opacity = 1;
        }, startAt + i * colourStaggerMs)
      );
    });
    return () => timeouts.forEach(clearTimeout);
  }, [play, colourShapes.length, durationMs, colourFadeMs, colourStaggerMs]);

  // Sketch line timing — per-stroke duration scales with length, small jitter
  // on start times for a hand-drawn feel.
  const penSpeed = 3.6; // viewBox px / ms
  const minDur = 90;
  const maxDur = 700;

  return (
    <svg
      ref={svgRef}
      viewBox="0 0 2048 1448"
      width="100%"
      height="auto"
      preserveAspectRatio="xMidYMid meet"
      fill="none"
      stroke={color}
      strokeWidth={strokeWidth}
      strokeLinecap="round"
      strokeLinejoin="round"
      vectorEffect="non-scaling-stroke"
      style={{ display: "block" }}
    >
      {/* Watercolour washes — rendered as proper SVG elements so they actually
          paint (innerHTML on an SVG node creates HTML elements, not SVG). */}
      {showColour && colourShapes.length > 0 && (
        <g ref={colourGroupRef} style={{ pointerEvents: "none" }}>
          {colourShapes.map((shape) => {
            // The source SVG wraps every colour path in two nested <g
            // transform="..."> tags — preserve them so the path lands in the
            // right place.
            const inner = (
              <path
                key={shape.id}
                id={shape.id}
                d={shape.d}
                fill={shape.fill}
                fillOpacity={shape.opacity}
                stroke="none"
              />
            );
            return (
              <g key={shape.id} transform={shape.transforms[0]}>
                <g transform={shape.transforms[1]}>{inner}</g>
              </g>
            );
          })}
        </g>
      )}

      {/* Sketch ink lines */}
      <g vectorEffect="non-scaling-stroke">
        {sketchPaths.map((p, i) => {
          const t = N > 1 ? i / (N - 1) : 0;
          const baseDelay = t * durationMs * 0.94;
          const h = ((i * 9301 + 49297) % 233280) / 233280;
          const jitter = (h - 0.5) * 220;
          const delay = Math.max(0, baseDelay + jitter);
          const lenDur = Math.min(maxDur, Math.max(minDur, p.len / penSpeed));
          return (
            <path
              key={p.id}
              d={p.d}
              strokeDasharray={p.len}
              strokeDashoffset={play ? 0 : p.len}
              style={{
                transition: `stroke-dashoffset ${lenDur}ms cubic-bezier(.45,.05,.55,.95) ${delay}ms`,
              }}
            />
          );
        })}
      </g>
    </svg>
  );
};

window.StClementsSketch = StClementsSketch;
