// ShopScene.ts: 杂货店. 咪咪 (mimi - text corruption carrier), shelves (C5), count shelves (T5).
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 } from '../UIScene';
import { audio } from '../../systems/AudioEngine';

export class ShopScene extends MapScene {
  mimiSprite!: Phaser.GameObjects.Sprite;
  constructor() { super('ShopScene', 'map:shop', 'shop'); }

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

    this.addInteract(7, 7, () => this.talkMimi(), { promptText: '按 E 和咪咪说话' });
    // shelves C5 (from D2) + T5 count (D2): merged interaction on shelves
    this.addInteract(2, 2, () => {
      // T5 count (D2): completing the count task
      if (director.day === 2 && !director.tasksDone.has('T5')) {
        story.completeTask('T5', 10);
        audio.sfxDone();
      }
      if (director.day >= 2) {
        const got = director.discoverClue('C5');
        this.say([{ speaker:'咪咪', npcKey:'mimi', portrait: NPCS.mimi.portrait.smile, text:'数清楚啦？太谢谢你啦！' },
                  { speaker:'', text: got ? '货架上同一商品重复排了 9 格，标签全是空白的。' : '货架上的商品……好像都一模一样。' }]);
      } else {
        this.say([{ speaker:'', text:'货架上商品满满当当。' }]);
      }
    }, { promptText: '按 E 看货架' });
  }

  talkMimi() {
    if (director.noteNpcTalk('mimi')) director.sadness('对同一 NPC 一天内对话 ≥5 次（纠缠）', 'mimi');
    story.recordGreet('mimi');
    // letter deliver (T4 day2)
    if (director.day === 2 && story.lettersTaken[2]) {
      story.deliverLetter('mimi', (l) => this.say(l));
      return;
    }
    // bread deliver (T1/T8)
    if ((director.day === 1 || director.day === 4) && story.breadTaken[director.day]) {
      story.deliverBread('mimi', (l) => this.say(l));
      return;
    }
    this.say(story.npcTalk('mimi'));
  }

  countShelves() {
    story.completeTask('T5', 10);
    audio.sfxDone();
    this.say([{ speaker:'咪咪', npcKey:'mimi', portrait: NPCS.mimi.portrait.smile, text:'数清楚啦？太谢谢你啦！大家都要开开心心的哦。' }]);
  }
}
