import Phaser from 'phaser';
import { installHarness } from '../dev';

export const STAGE_W = 1280;
export const STAGE_H = 720;
export const FLOOR_Y = 640;

/** A physics body paired with the flat black silhouette that renders it.
 *  This is the whole game's render contract: the body is truth, the shape follows. */
export interface Prop {
  body: MatterJS.BodyType;
  view: Phaser.GameObjects.Shape;
}

/**
 * The kitchen stage. Matter's auto-step is OFF so the sim advances only when we
 * call stepSim — deterministic, drivable frame-by-frame from the dev harness.
 * In normal play scene.update drives one fixed step per frame; the harness sets
 * auto=false and steps itself.
 */
export class Stage extends Phaser.Scene {
  auto = true;
  props: Prop[] = [];
  box!: MatterJS.BodyType;

  constructor() {
    super('stage');
  }

  create(): void {
    this.matter.world.autoUpdate = false;

    // floor + side walls so nothing wanders off before there are stage edges to care about
    this.addBody(this.matter.add.rectangle(STAGE_W / 2, FLOOR_Y + 20, STAGE_W, 40, { isStatic: true }), STAGE_W, 40, 0x2a211a);
    this.matter.add.rectangle(-20, STAGE_H / 2, 40, STAGE_H * 2, { isStatic: true });
    this.matter.add.rectangle(STAGE_W + 20, STAGE_H / 2, 40, STAGE_H * 2, { isStatic: true });

    // M0: a single box that drops onto the floor and comes to rest.
    this.box = this.matter.add.rectangle(STAGE_W / 2, 80, 64, 64, { restitution: 0.15, friction: 0.6 });
    this.addBody(this.box, 64, 64, 0x111111);

    installHarness(this);
  }

  /** Register a body with a flat silhouette that tracks it. */
  addBody(body: MatterJS.BodyType, w: number, h: number, color: number): MatterJS.BodyType {
    const view = this.add.rectangle(body.position.x, body.position.y, w, h, color);
    this.props.push({ body, view });
    return body;
  }

  stepSim(dt = 1000 / 60): void {
    this.matter.world.step(dt);
  }

  update(): void {
    if (this.auto) this.stepSim();
    for (const p of this.props) {
      p.view.setPosition(p.body.position.x, p.body.position.y);
      p.view.setRotation(p.body.angle);
    }
  }
}
