import { _decorator, Component, BoxCollider2D, Contact2DType, IPhysics2DContact, Node, Color } from 'cc';
import { Fruit } from './Fruit';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

@ccclass('TopSensor')
export class TopSensor extends Component {
  @property(GameManager)
  game!: GameManager;

  @property
  holdSeconds = 2.0; // 触顶持续秒数

  private touching = new Map<Node, number>(); // node -> enterTime

  onEnable() {
    const col = this.getComponent(BoxCollider2D)!;
    col.sensor = true;
    col.on(Contact2DType.BEGIN_CONTACT, this.onBegin, this);
    col.on(Contact2DType.END_CONTACT, this.onEnd, this);
  }
  onDisable() {
    const col = this.getComponent(BoxCollider2D)!;
    col.off(Contact2DType.BEGIN_CONTACT, this.onBegin, this);
    col.off(Contact2DType.END_CONTACT, this.onEnd, this);
  }

  private onBegin(_self: BoxCollider2D, other: any, _c: IPhysics2DContact | null) {
    const f = (other.node as Node).getComponent(Fruit);
    if (f) this.touching.set(other.node, performance.now() / 1000);
  }
  private onEnd(_self: BoxCollider2D, other: any) {
    this.touching.delete(other.node);
  }

  update() {
    if (!this.game || this.game.isGameOver) return;
    const now = performance.now() / 1000;
    for (const [node, t] of this.touching) {
      if (now - t >= this.holdSeconds) {
        this.game.onGameOver();
        break;
      }
    }
    // 可选：把状态交给 GameManager 显示红线闪烁
    this.game.setDanger(this.touching.size > 0);
  }
}