import Phaser from 'phaser';
import { sfx, music } from '../game/audio';
import { STRING_STYLES, type StringStyle } from '../sim/marionette';
import { loadProgress } from '../game/progress';
import { DAYS } from '../game/game';

/**
 * Title card, launched as an overlay over the live stage so the dev harness is
 * available underneath from frame one. Pick your strings (difficulty modifier),
 * then click to begin — the stage restarts with the chosen string style, and
 * that first click also unblocks audio so the shamisen sting lands.
 */
export class Title extends Phaser.Scene {
  constructor() {
    super('title');
  }

  create(): void {
    const W = this.scale.width, H = this.scale.height;
    this.add.rectangle(W / 2, H / 2, W, H, 0x0a0705, 0.82);

    if (this.textures.exists('title_art')) {
      this.add.image(W / 2, H * 0.34, 'title_art').setScale(0.56).setDepth(1);
    }

    this.add.text(W / 2, H * 0.6, 'サンドニエット', { fontFamily: 'serif', fontSize: '52px', color: '#efe4cb' })
      .setOrigin(0.5).setDepth(1);
    this.add.text(W / 2, H * 0.66, 'S A N D O N I E T T E', { fontFamily: 'serif', fontSize: '18px', color: '#c8a24a' })
      .setOrigin(0.5).setDepth(1);

    // ---- string select: the unlockables-as-difficulty row ----
    const styles = Object.keys(STRING_STYLES) as StringStyle[];
    const picked = ((this.registry.get('sando.style') as StringStyle) ?? 'hemp');
    const labels = new Map<StringStyle, Phaser.GameObjects.Text>();
    const paint = (sel: StringStyle): void => {
      for (const [k, t] of labels) {
        t.setColor(k === sel ? '#e8b84a' : '#8a7a5a');
        t.setText(k === sel ? `▸ ${k.toUpperCase()} ◂` : k.toUpperCase());
      }
      blurb.setText(STRING_STYLES[sel].blurb);
    };
    styles.forEach((k, i) => {
      const t = this.add.text(W / 2 + (i - (styles.length - 1) / 2) * 150, H * 0.76, k.toUpperCase(), {
        fontFamily: 'monospace', fontSize: '18px', color: '#8a7a5a',
      }).setOrigin(0.5).setDepth(2).setInteractive({ useHandCursor: true });
      t.on('pointerdown', (_p: unknown, __x: unknown, ___y: unknown, ev?: { stopPropagation?: () => void }) => {
        ev?.stopPropagation?.();
        this.registry.set('sando.style', k);
        sfx.enable();
        sfx.shamisen();
        paint(k);
      });
      labels.set(k, t);
    });
    const blurb = this.add.text(W / 2, H * 0.81, '', { fontFamily: 'serif', fontSize: '14px', color: '#9a8a6a', fontStyle: 'italic' })
      .setOrigin(0.5).setDepth(1);
    paint(picked);

    const shout = this.add.text(W / 2, H * 0.89, 'SHUBATTO!!  SANDONIETTE!!!', {
      fontFamily: 'serif', fontSize: '22px', color: '#e8b84a', fontStyle: 'bold',
    }).setOrigin(0.5).setDepth(1);
    this.tweens.add({ targets: shout, scale: 1.12, duration: 600, yoyo: true, repeat: -1, ease: 'Sine.inOut' });

    const hint = this.add.text(W / 2, H * 0.95, 'click to begin', { fontFamily: 'serif', fontSize: '15px', color: '#9a8a6a' })
      .setOrigin(0.5).setDepth(1);
    this.tweens.add({ targets: hint, alpha: 0.3, duration: 900, yoyo: true, repeat: -1 });

    // the trophy shelf: best-grade hanko stamps for cleared days (localStorage)
    const best = loadProgress().best;
    if (Object.keys(best).length > 0) {
      DAYS.forEach((_, i) => {
        if (best[i] === undefined) return;
        const x = W - 46, y = 90 + i * 56;
        if (this.textures.exists('day_stamp')) this.add.image(x, y, 'day_stamp').setDisplaySize(44, 44).setAlpha(0.85).setDepth(2);
        else this.add.circle(x, y, 20, 0x8a1a12, 0.8).setDepth(2);
        this.add.text(x, y, best[i], { fontFamily: 'serif', fontSize: '20px', color: '#f4e8c4' }).setOrigin(0.5).setDepth(3);
        this.add.text(x - 32, y, `${i + 1}`, { fontFamily: 'monospace', fontSize: '11px', color: '#8a7a5a' }).setOrigin(0.5).setDepth(2);
      });
    }

    // begin: anywhere that isn't a style button. Restart the stage so the puppet
    // is strung with the chosen style, then drop the overlay.
    this.input.on('pointerdown', (_p: Phaser.Input.Pointer, over: unknown[]) => {
      if (over.length > 0) return; // that click was a style pick
      sfx.enable();
      sfx.gong();
      sfx.shamisen();
      music.start();
      this.registry.set('sando.started', true);
      this.scene.get('stage').scene.restart();
      this.scene.stop();
    });
  }
}
