// PlazaScene.ts: hub. NPC 阿福 + twin birds. Board (announcements), flowerbeds (T2/T9 water),
// greet point (T3/T10), ribbons (T13), T14 smile spot, festival (T15).
import Phaser from 'phaser';
import { MapScene } from '../MapScene';
import { director } from '../../systems/CorruptionDirector';
import { story } from '../../systems/StoryDirector';
import { NPCS, AFU_ANNOUNCE, T14_DURATION, T14_SILENCE_START } from '../../data/gamedata';
import { DialogueLine, DialogueChoice } from '../UIScene';
import { audio } from '../../systems/AudioEngine';

export class PlazaScene extends MapScene {
  afuSprite!: Phaser.GameObjects.Sprite;
  dabaoSprite!: Phaser.GameObjects.Sprite;
  birdSprite!: Phaser.GameObjects.Sprite;
  ribbons: Phaser.GameObjects.Image[] = [];
  rainGfx: Phaser.GameObjects.Graphics | null = null;
  raining = false;
  rainTimer = 0;

  constructor() { super('PlazaScene', 'map:plaza', 'plaza'); }

  onBuild(map: Phaser.Tilemaps.Tilemap, ts: Phaser.Tilemaps.Tileset) {
    // 阿福 at board
    this.afuSprite = this.add.sprite(8*16+8, 8*16+8, 'npc', NPCS.afu.fieldSprite).setOrigin(0.5, 0.9);
    (this.afuSprite as any).npcKey = 'afu';
    this.npcSprites.push(this.afuSprite);
    // 大宝 (postman) at village gate (left side of plaza)
    this.dabaoSprite = this.add.sprite(3*16+8, 6*16+8, 'npc', NPCS.dabao.fieldSprite).setOrigin(0.5, 0.9);
    (this.dabaoSprite as any).npcKey = 'dabao';
    this.npcSprites.push(this.dabaoSprite);
    // twin birds on tree (flapping)
    this.birdSprite = this.add.sprite(15*16+8, 3*16+8, 'npc', 15).setOrigin(0.5,0.9);
    this.birdSprite.play('bird-flap');
    (this.birdSprite as any).npcKey = 'bird';
    this.npcSprites.push(this.birdSprite);

    // interact: talk to afu
    this.addInteract(8, 8, () => this.talkAfu(), { promptText: '按 E 和阿福说话' });
    // interact: 大宝 (greet + letter pickup T4 + bread deliver)
    this.addInteract(3, 6, () => this.talkDabao(), { promptText: '按 E 和大宝说话' });
    // interact: board -> announcement + today's tasks
    this.addInteract(7, 7, () => this.readBoard(), { promptText: '按 E 看公告板' });
    // interact: birds
    this.addInteract(15, 2, () => {
      story.recordGreet('bird');
      this.say([{ speaker:'双子鸟', npcKey:'bird', portrait: NPCS.bird.portrait.smile, text:'（鸟儿欢快地歌唱着，歌声里好像有些……单调？）' }]);
    }, { promptText: '按 E 听鸟鸣' });

    // flowerbed water points (T2 day1 / T9 day4)
    const waterPoints = [[4,4],[5,4],[4,5]];
    waterPoints.forEach(([tx,ty], i) => {
      this.addInteract(tx, ty, () => this.waterFlower(i), { promptText: '按 E 浇花' });
    });

    // plaza scenery marker (moved away from smile spot to avoid conflict)
    this.addInteract(20, 12, () => {
      this.say([{ speaker:'', text:'广场上阳光明媚，花儿开得很艳。' }]);
    }, { promptText: '按 E 看花坛' });

    // ribbon hang points (T13 day6)
    const ribbonPoints = [[10,3],[20,3],[10,14],[20,14]];
    ribbonPoints.forEach(([tx,ty], i) => {
      this.addInteract(tx, ty, () => this.hangRibbon(i, tx, ty), {
        promptText: '按 E 挂彩带',
        enabled: () => director.day === 6 && !director.tasksDone.has('T13-done-'+i),
      });
    });

    // T14 smile spot (day6): standing near center triggers when idle handled elsewhere
    this.addInteract(15, 10, () => this.startSmileTask(), {
      promptText: '按 E 保持微笑',
      enabled: () => director.day === 6 && !director.tasksDone.has('T14'),
    });

    // festival (day7): board leads to T15
    this.addInteract(7, 7, () => this.festival(), {
      promptText: '按 E 参加庆典',
      enabled: () => director.day === 7,
    });

    // T12 wipe board (day5, can refuse) -> C6
    this.addInteract(7, 7, () => this.wipeBoard(), {
      promptText: '按 E 擦公告板',
      enabled: () => director.day === 5 && !director.tasksDone.has('T12'),
    });

    // extras (群演) walking
    this.spawnExtras();

    // Day6 evening rain
    if (director.day === 6 && story.phase === 'evening') this.startRain();
  }

  spawnExtras() {
    const positions = [[12,12],[18,12],[22,8],[6,6],[24,6]];
    positions.forEach((p, i) => {
      const sp = this.add.sprite(p[0]*16+8, p[1]*16+8, 'npc', 20 + (i%5)).setOrigin(0.5,0.9);
      (sp as any).npcKey = 'extra'+i;
      this.npcSprites.push(sp);
      // gentle wander
      this.time.addEvent({ delay: 1500 + i*300, loop: true, callback: () => {
        // S4: one extra stops and faces player
        if (director.stage === 'S4' && i === 0) { sp.setFlipX(this.player.x < sp.x); return; }
        sp.x += Phaser.Math.Between(-8,8); sp.y += Phaser.Math.Between(-8,8);
        sp.setFlipX(this.player.x < sp.x);
      }});
    });
  }

  talkAfu() {
    if (director.noteNpcTalk('afu')) director.sadness('对同一 NPC 一天内对话 ≥5 次（纠缠）', 'afu');
    story.recordGreet('afu');
    this.say(story.npcTalk('afu'));
  }

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

  readBoard() {
    // show announcement (verbatim)
    const lines = story.announcementLines();
    // also list today's tasks
    const tasks = story.todayTasks();
    const taskLine = tasks.length ? `今日任务：${tasks.map(t=>t.id).join('、')}` : '今天公告板空空的。';
    lines.push({ speaker:'', text: taskLine });
    this.say(lines);
  }

  waterFlower(idx: number) {
    // T2 (day1) / T9 (day4)
    const isWaterDay = director.day === 1 || director.day === 4;
    const taskId = director.day === 1 ? 'T2' : 'T9';
    if (isWaterDay) {
      const key = `${taskId}@${idx}`;
      if (!director.tasksDone.has(key)) {
        director.tasksDone.add(key);
        director.smallInteraction('water');
        const count = director.day === 1 ? 3 : 3;
        const done = [0,1,2].filter(i => director.tasksDone.has(`${taskId}@${i}`)).length;
        this.say([{ speaker:'', text:'花儿喝饱了水，开得更艳了。' }]);
        if (done >= count) story.completeTask(taskId, 10);
      } else {
        this.say([{ speaker:'', text:'这株已经浇过了。' }]);
      }
    } else {
      director.smallInteraction('water');
      this.say([{ speaker:'', text:'花儿喝饱了水。' }]);
    }
  }

  hangRibbon(i: number, tx: number, ty: number) {
    director.tasksDone.add('T13-done-'+i);
    const rib = this.add.image(tx*16+8, ty*16+8, 'tileset', 35).setOrigin(0.5,0.5).setDepth(20);
    this.ribbons.push(rib);
    director.smallInteraction('ribbon');
    audio.sfxDone();
    const hung = [0,1,2,3].filter(k => director.tasksDone.has('T13-done-'+k)).length;
    if (hung >= 4) story.completeTask('T13', 10);
    this.say([{ speaker:'', text:'彩带挂好了，真漂亮。' }]);
  }

  startSmileTask() {
    // T14: stand still 60s, camera zoom in, all NPCs face player, 40s sound fades
    director.tasksDone.add('T14');
    this.player.atTaskPoint = true; // don't count as 发呆 during smile task
    const cam = this.cameras.main;
    const startZoom = cam.zoom;
    const startTime = this.time.now;
    // freeze player movement by setting a flag via player
    (this.player as any).frozen = true;
    // all npcs face player
    this.npcSprites.forEach(s => s.setFlipX(this.player.x < s.x));
    audio.sfxBell();
    const overlay = this.add.text(160, 20, '保持微笑……', { fontFamily:'monospace', fontSize:'9px', color:'#ffd86b' }).setOrigin(0.5).setScrollFactor(0).setDepth(7000);
    let silenceSet = false;
    const ev = this.time.addEvent({ delay: 200, loop: true, callback: () => {
      const elapsed = (this.time.now - startTime)/1000;
      // zoom in slowly from 1 to 1.8 over 60s
      cam.zoom = startZoom + (1.0) * (elapsed / T14_DURATION);
      // sound fade 40-60s
      if (elapsed >= T14_SILENCE_START) {
        const f = 1 - (elapsed - T14_SILENCE_START) / (T14_DURATION - T14_SILENCE_START);
        audio.setSilenceFactor(Math.max(0, f));
        silenceSet = true;
      }
      if (elapsed >= T14_DURATION) {
        ev.remove();
        (this.player as any).frozen = false;
        this.player.atTaskPoint = false;
        cam.zoom = startZoom;
        audio.setSilenceFactor(1.0);
        overlay.destroy();
        story.completeTask('T14', 15);
        this.say([{ speaker:'阿福', npcKey:'afu', portrait: NPCS.afu.portrait.smile, text:'做得真好。你笑得真好看。' }]);
      }
    }});
  }

  festival() {
    // T15 -> ending
    director.tasksDone.add('T15');
    this.scene.stop('UIScene');
    this.scene.stop('DebugScene');
    this.scene.start('EndingScene', { ending: director.determineEnding() });
  }

  wipeBoard() {
    const choices: DialogueChoice[] = [
      { label: '好，我来擦（温柔）', type: 'gentle' },
      { label: '这字迹……（迟疑）', type: 'doubt' },
      { label: '不想擦（拒绝）', type: 'deny' },
    ];
    this.say([
      { speaker:'', text:'公告板上落了灰。' },
      { speaker:'阿福', npcKey:'afu', portrait: NPCS.afu.portrait.smile, text:'帮忙擦擦公告板好吗？', choices },
    ], undefined, (c: DialogueChoice) => {
      if (c.type === 'deny') {
        director.rejectedTasks.add('T12');
        director.sadness('拒绝任务', 'afu');
        this.say([{ speaker:'阿福', npcKey:'afu', portrait: NPCS.afu.portrait.smile, text:'没关系哦。' }]);
      } else {
        story.completeTask('T12', 10);
        audio.sfxDone();
        director.discoverClue('C6');
        this.say([{ speaker:'', text:'擦到一半，浮现出旧字迹：' },
          { speaker:'', text:'「第 412 届丰收庆典」上覆盖着更早的「第 411 届」「第 410 届」……' }]);
      }
    });
  }

  startRain() {
    this.raining = true;
    this.rainGfx = this.add.graphics().setDepth(4000);
    this.time.addEvent({ delay: 60, loop: true, callback: () => this.drawRain() });
  }
  private drawRain() {
    if (!this.rainGfx) return;
    this.rainGfx.clear();
    this.rainGfx.fillStyle(0x9bb8d0, 0.5);
    for (let i=0;i<60;i++) {
      const x = Phaser.Math.Between(0, 320*3), y = Phaser.Math.Between(0, 180*3);
      this.rainGfx.fillRect((x + this.time.now*0.1)%480 - 80, (y + this.time.now*0.2)%300 - 60, 1, 4);
    }
    // rain in rain stand detection handled in update below via director
  }

  update(time: number, delta: number) {
    super.update(time, delta);
    // Day6 evening rain sadness: stand in rain >=10s
    if (this.raining) {
      // assume whole plaza is "in rain"
      if (this.player.moving === false) {
        this.rainTimer += delta;
      } else this.rainTimer = 0;
      if (this.rainTimer >= 10000) {
        this.rainTimer = 0;
        director.sadness('雨天（Day 6）站在雨里 ≥10 秒', this.nearestNpcKey());
      }
    }
    // NPC dialogue reaction to rain = zero reaction (by design, NPCs say nothing about rain)
    // bird flap freeze when S2+ music detuned
    if (director.stage === 'S2' || director.stage === 'S3') {
      // stutter animation
      if (Math.random() < 0.02) this.birdSprite.anims.pause();
      else this.birdSprite.anims.resume();
    }
  }
}
