// BakeryScene.ts: 面包房. 圆圆 (baker), recipe paper (C2 from D3), knead (T11 D5, can refuse), bread pickup (T1/T8).
import Phaser from 'phaser';
import { MapScene } from '../MapScene';
import { director } from '../../systems/CorruptionDirector';
import { story } from '../../systems/StoryDirector';
import { NPCS } from '../../data/gamedata';
import { DialogueLine, DialogueChoice } from '../UIScene';
import { audio } from '../../systems/AudioEngine';

export class BakeryScene extends MapScene {
  yySprite!: Phaser.GameObjects.Sprite;
  constructor() { super('BakeryScene', 'map:bakery', 'bakery'); }

  onBuild(map: Phaser.Tilemaps.Tilemap, ts: Phaser.Tilemaps.Tileset) {
    this.yySprite = this.add.sprite(3*16+8, 7*16+8, 'npc', NPCS.yuanyuan.fieldSprite).setOrigin(0.5,0.9);
    (this.yySprite as any).npcKey = 'yuanyuan';
    this.npcSprites.push(this.yySprite);

    // talk to yuanyuan
    this.addInteract(3, 7, () => this.talkYY(), { promptText: '按 E 和圆圆说话' });
    // recipe paper (C2 from D3)
    this.addInteract(11, 5, () => {
      if (director.day >= 3) {
        const got = director.discoverClue('C2');
        this.say([{ speaker:'', text: got ? '配方纸背面写着：「按疗程配比。甜度：最大。」' : '配方纸背面那行字还在。' }]);
      } else {
        this.say([{ speaker:'', text:'一张蜂蜜面包的配方。' }]);
      }
    }, { promptText: '按 E 看配方纸' });

    // knead dough (T11 D5, can refuse)
    this.addInteract(3, 6, () => this.knead(), { promptText: '按 E 揉面', enabled: () => director.day === 5 && !director.tasksDone.has('T11') });
    // bread pickup for T1/T8 (take honey bread to deliver)
    this.addInteract(2, 5, () => this.takeBread(), { promptText: '按 E 取面包', enabled: () => (director.day === 1 || director.day === 4) });
  }

  talkYY() {
    if (director.noteNpcTalk('yuanyuan')) director.sadness('对同一 NPC 一天内对话 ≥5 次（纠缠）', 'yuanyuan');
    story.recordGreet('yuanyuan');
    // letter deliver (T4 day2)
    if (director.day === 2 && story.lettersTaken[2]) {
      story.deliverLetter('yuanyuan', (l) => this.say(l));
      return;
    }
    this.say(story.npcTalk('yuanyuan'));
  }

  takeBread() {
    story.takeBread((l) => this.say(l));
  }

  knead() {
    const choices: DialogueChoice[] = [
      { label: '好呀，我来帮你（温柔）', type: 'gentle' },
      { label: '我……不太想（迟疑）', type: 'doubt' },
      { label: '不想做（拒绝）', type: 'deny' },
    ];
    this.say([
      { speaker:'圆圆', npcKey:'yuanyuan', portrait: NPCS.yuanyuan.portrait.smile, text:'能帮我揉揉面吗？', choices },
    ], undefined, (c: DialogueChoice) => {
      if (c.type === 'deny') {
        director.rejectedTasks.add('T11');
        director.sadness('拒绝任务', 'yuanyuan');
        this.say([{ speaker:'圆圆', npcKey:'yuanyuan', portrait: NPCS.yuanyuan.portrait.smile, text:'没关系哦，那……也没关系。' }]);
      } else {
        story.completeTask('T11', 10);
        audio.sfxDone();
        this.say([{ speaker:'圆圆', npcKey:'yuanyuan', portrait: NPCS.yuanyuan.portrait.smile, text:'谢谢你！面团好软，对不对？' }]);
      }
    });
  }
}
