// Fish — multiple pairs of tiny faded fish that swim together.
// Each pair shares a color; click any fish and that pair darts away.

const Fish = () => {
  const [, setTick] = React.useState(0);

  // Pair configs — each pair has its own color and starting position.
  const pairsRef = React.useRef(null);
  if (pairsRef.current === null) {
    const vw = window.innerWidth;
    const vh = window.innerHeight;

    const makePair = (config) => {
      const { color, fin, startYRatio, size } = config;
      const leaderX = Math.random() * vw;
      const leaderY = vh * startYRatio;
      const dir = Math.random() < 0.5 ? -1 : 1;
      const baseVx = dir * (14 + Math.random() * 6);
      return [
        {
          id: Math.random(),
          x: leaderX, y: leaderY,
          vx: baseVx, vy: 0,
          size: size,
          color, fin,
          phase: Math.random() * Math.PI * 2,
          wiggleHz: 5.5 + Math.random(),
          dispersed: 0, panicVx: 0, panicVy: 0,
          isLeader: true,
          pairId: config.pairId,
        },
        {
          id: Math.random(),
          x: leaderX - dir * 22, y: leaderY + 6,
          vx: baseVx, vy: 0,
          size: size * 0.9,
          color, fin,
          phase: Math.random() * Math.PI * 2,
          wiggleHz: 6 + Math.random(),
          dispersed: 0, panicVx: 0, panicVy: 0,
          isLeader: false,
          pairId: config.pairId,
        },
      ];
    };

    pairsRef.current = [
      makePair({ pairId: 0, color: '#6A93A8', fin: '#4A7389', startYRatio: 0.78 + Math.random() * 0.08, size: 0.95 }),
      makePair({ pairId: 1, color: '#C97A6A', fin: '#8A4A3A', startYRatio: 0.85 + Math.random() * 0.08, size: 0.9  }),
      makePair({ pairId: 2, color: '#7A9E82', fin: '#4E7A5A', startYRatio: 0.82 + Math.random() * 0.08, size: 0.85 }),
      makePair({ pairId: 3, color: '#B8956A', fin: '#8A6A40', startYRatio: 0.80 + Math.random() * 0.08, size: 0.78 }),
      makePair({ pairId: 4, color: '#8A7AB8', fin: '#5A4A8A', startYRatio: 0.88 + Math.random() * 0.06, size: 0.72 }),
      makePair({ pairId: 5, color: '#5A8FA0', fin: '#3A6A7A', startYRatio: 0.75 + Math.random() * 0.10, size: 1.05 }),
    ].flat();
  }

  React.useEffect(() => {
    let raf;
    let lastT = performance.now();
    const loop = (now) => {
      const dt = Math.min(0.05, (now - lastT) / 1000);
      lastT = now;

      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const surfaceFn = window.__tides?.surfaceY;

      // Group fish by pair
      const all = pairsRef.current;
      const byPair = {};
      all.forEach(f => { (byPair[f.pairId] = byPair[f.pairId] || []).push(f); });

      Object.values(byPair).forEach(([leader, follower]) => {
        // LEADER
        if (leader.dispersed > 0) leader.dispersed = Math.max(0, leader.dispersed - dt * 0.6);
        leader.x += (leader.vx + leader.panicVx * leader.dispersed) * dt;
        leader.y += (leader.vy + leader.panicVy * leader.dispersed) * dt;
        leader.panicVx *= (1 - dt * 1.2);
        leader.panicVy *= (1 - dt * 1.2);
        leader.vy += (Math.sin(now / 1000 * 0.35 + leader.phase) * 5 - leader.vy) * dt * 0.6;
        if (Math.random() < 0.004) {
          leader.vx += (Math.random() - 0.5) * 8;
          leader.vx = Math.max(-30, Math.min(30, leader.vx));
          if (Math.abs(leader.vx) < 10) leader.vx = (leader.vx >= 0 ? 1 : -1) * 10;
        }
        if (leader.x < -60) leader.x = vw + 60;
        if (leader.x > vw + 60) leader.x = -60;
        const surface = surfaceFn ? surfaceFn(leader.x) : vh * 0.65;
        const minY = surface + 24;
        const maxY = vh - 30;
        if (leader.y < minY) { leader.y = minY; leader.vy = Math.abs(leader.vy) + 3; }
        if (leader.y > maxY) { leader.y = maxY; leader.vy = -Math.abs(leader.vy) - 3; }

        // FOLLOWER
        if (follower.dispersed > 0) follower.dispersed = Math.max(0, follower.dispersed - dt * 0.6);
        const facing = leader.vx >= 0 ? 1 : -1;
        const targetX = leader.x - facing * 20;
        const targetY = leader.y + 7;
        const stiffness = 4.0;
        const damping = 2.2;
        const ax = (targetX - follower.x) * stiffness - follower.vx * damping;
        const ay = (targetY - follower.y) * stiffness - follower.vy * damping;
        follower.vx += ax * dt;
        follower.vy += ay * dt;
        follower.x += (follower.vx + follower.panicVx * follower.dispersed) * dt;
        follower.y += (follower.vy + follower.panicVy * follower.dispersed) * dt;
        follower.panicVx *= (1 - dt * 1.2);
        follower.panicVy *= (1 - dt * 1.2);
        const fSurface = surfaceFn ? surfaceFn(follower.x) : vh * 0.65;
        if (follower.y < fSurface + 20) follower.y = fSurface + 20;
        if (follower.y > vh - 28) follower.y = vh - 28;
      });

      setTick(t => (t + 1) % 1000000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  const dispersePair = (pairId, clickX, clickY) => {
    pairsRef.current.forEach(f => {
      if (f.pairId !== pairId) return;
      const dx = f.x - clickX;
      const dy = f.y - clickY;
      const dist = Math.max(20, Math.hypot(dx, dy));
      const nx = dx / dist;
      const ny = dy / dist;
      const force = 260;
      f.panicVx = nx * force;
      f.panicVy = ny * force * 0.5;
      f.dispersed = 1;
      f.vx = Math.sign(nx) * Math.max(20, Math.abs(f.vx));
    });
  };

  const onFishClick = (e, f) => {
    e.stopPropagation();
    dispersePair(f.pairId, f.x, f.y);
  };

  const t = performance.now() / 1000;

  return (
    <svg
      style={{
        position: 'fixed',
        inset: 0,
        width: '100vw',
        height: '100vh',
        pointerEvents: 'none',
        zIndex: 3,
      }}
    >
      {pairsRef.current.map(f => {
        const facing = f.vx >= 0 ? 1 : -1;
        const wiggle = Math.sin(t * f.wiggleHz + f.phase) * 10;
        const scale = f.size;
        return (
          <g
            key={f.id}
            transform={`translate(${f.x}, ${f.y}) scale(${facing * scale}, ${scale})`}
            style={{
              pointerEvents: 'auto',
              cursor: 'none',
              opacity: 0.75,
            }}
            onClick={(e) => onFishClick(e, f)}
          >
            <circle r="22" fill="transparent" />
            <g transform={`translate(-12, 0) rotate(${wiggle})`}>
              <path d="M 0 0 L -9 -5 L -7 0 L -9 5 Z" fill={f.fin} />
            </g>
            <ellipse cx="0" cy="0" rx="11" ry="4.5" fill={f.color} />
            <circle cx="7" cy="-1" r="0.9" fill="#1A3A4A" />
          </g>
        );
      })}
    </svg>
  );
};

window.Fish = Fish;
