// petals.jsx — slow, irregular sakura petal field (tweakable)

const PETAL_SRCS = Array.from({length: 13}, (_, i) => `assets/petal-${i+1}.png`);

function rand(a, b) { return a + Math.random() * (b - a); }
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }

function Petal({ index, speed, blurMult }) {
  const depth = React.useMemo(() => Math.random(), []);
  const cfg = React.useMemo(() => {
    const src = pick(PETAL_SRCS);
    const size = 28 + depth * 78;
    const startX = rand(-5, 105);
    const drift = rand(-22, 22);
    const baseDur = 16 + (1 - depth) * 22 + rand(-4, 4);
    const duration = baseDur / Math.max(0.25, speed);
    const delay = -rand(0, duration);
    const rotateStart = rand(0, 360);
    const rotateEnd = rotateStart + rand(180, 720) * (Math.random() < 0.5 ? -1 : 1);
    const sway = rand(40, 140);
    const swayPeriod = rand(2.4, 5.2) / Math.max(0.25, speed);
    const baseBlur = depth < 0.18 ? rand(2.4, 4.2) : (depth > 0.85 ? rand(0.4, 1.0) : rand(0, 0.6));
    const blur = baseBlur * blurMult;
    const opacityMax = 0.45 + depth * 0.55;
    return { src, size, startX, drift, duration, delay, rotateStart, rotateEnd, sway, swayPeriod, blur, opacityMax, depth };
  }, [speed, blurMult]);

  const style = {
    width: cfg.size,
    height: cfg.size,
    left: `${cfg.startX}vw`,
    filter: `blur(${cfg.blur}px)`,
    animation: `petalFall${index} ${cfg.duration}s linear ${cfg.delay}s infinite, petalSway${index} ${cfg.swayPeriod}s ease-in-out ${cfg.delay}s infinite`,
    zIndex: Math.floor(cfg.depth * 10),
  };

  return (
    <div className="petal" style={style}>
      <style>{`
        @keyframes petalFall${index} {
          0%   { transform: translate3d(0, -12vh, 0) rotate(${cfg.rotateStart}deg); opacity: 0; }
          8%   { opacity: ${cfg.opacityMax}; }
          85%  { opacity: ${cfg.opacityMax * 0.9}; }
          100% { transform: translate3d(${cfg.drift}vw, 118vh, 0) rotate(${cfg.rotateEnd}deg); opacity: 0; }
        }
        @keyframes petalSway${index} {
          0%, 100% { margin-left: -${cfg.sway/2}px; }
          50%      { margin-left: ${cfg.sway/2}px; }
        }
      `}</style>
      <img src={cfg.src} alt="" />
    </div>
  );
}

function PetalField({ count = 22, speed = 1, blur = 1 }) {
  return (
    <div className="petals" aria-hidden="true">
      {Array.from({ length: Math.max(0, count) }).map((_, i) =>
        <Petal key={i} index={i} speed={speed} blurMult={blur} />
      )}
    </div>
  );
}

window.PetalField = PetalField;
