// output/boids-simulation/sim.js
import { Boid, SPEED } from './boid.js';

export class Simulation {
  constructor(canvas) {
    this.canvas = canvas;
    this.ctx = canvas.getContext('2d');
    this.boids = [];
    this.last = 0;
    this._raf = null;
    this.COUNT = 320; // hundreds of boids

    this.resize();
    this._initBoids();
  }

  _initBoids() {
    const w = this.canvas.width;
    const h = this.canvas.height;
    this.boids.length = 0;
    for (let i = 0; i < this.COUNT; i++) {
      const x = Math.random() * w;
      const y = Math.random() * h;
      const hue = Math.random() * 360;
      this.boids.push(new Boid(x, y, hue));
    }
  }

  start() {
    if (this._raf) return;
    this.last = performance.now();
    const tick = (ts) => {
      const dt = Math.min(0.033, (ts - this.last) / 1000 || 0.016);
      this.last = ts;
      this.update(dt);
      this.draw();
      this._raf = requestAnimationFrame(tick);
    };
    this._raf = requestAnimationFrame(tick);
  }

  stop() {
    if (this._raf) {
      cancelAnimationFrame(this._raf);
      this._raf = null;
    }
  }

  resize() {
    const w = window.innerWidth | 0;
    const h = window.innerHeight | 0;
    if (this.canvas.width !== w || this.canvas.height !== h) {
      this.canvas.width = w;
      this.canvas.height = h;
      // If boids list already exists, keep them; wrapping logic handles new bounds.
    }
  }

  update(dt) {
    const w = this.canvas.width;
    const h = this.canvas.height;
    // Update all boids
    for (let i = 0; i < this.boids.length; i++) {
      this.boids[i].update(this.boids, w, h, dt);
    }
  }

  draw() {
    const ctx = this.ctx;
    const w = this.canvas.width;
    const h = this.canvas.height;

    // Clear background
    ctx.clearRect(0, 0, w, h);

    // Draw all boids
    for (let i = 0; i < this.boids.length; i++) {
      this.boids[i].draw(ctx);
    }
  }
}
