import {
    IsometricTileMap,
    findPath,
    worldToScreen,
    screenToWorld,
    worldNorm,
    worldToTile,
    tileToWorld,
    moveTowardsW,
    FrameAnimation,
    Container,
    Sprite,
    Texture,
    type Vec2
} from '@rpg/engine';

/** Кадры героя по направлениям. side смотрит влево; вправо — флип. */
export interface HeroTextures {
    down: [Texture, Texture];
    up: [Texture, Texture];
    side: [Texture, Texture];
}

type Facing = 'down' | 'up' | 'left' | 'right';

/**
 * Управление героем: путь по клику (A*), плавное движение по маршруту,
 * покадровая анимация ходьбы по направлению движения.
 * Позиция — в мировых юнитах (1 юнит = 1 тайл, ноги героя).
 */
export class PlayerController {
    readonly view: Container;

    private sprite: Sprite;
    private anim: FrameAnimation;
    private facing: Facing = 'down';
    private textures: HeroTextures;

    /** Позиция в мировых юнитах (источник истины, ноги героя). */
    private pos: Vec2;
    private path: { x: number; y: number }[] = [];
    private waypoint: Vec2 | null = null;
    /** Скорость в мировых юнитах/сек. */
    private speed = 1.75;

    constructor(
        private map: IsometricTileMap,
        textures: HeroTextures,
        startTile: { x: number; y: number },
        private onStep?: () => void
    ) {
        this.textures = textures;

        this.view = new Container();
        this.sprite = new Sprite(textures.down[0]);
        this.sprite.anchor.set(0.5, 1); // ноги в точке позиции
        this.view.addChild(this.sprite);
        this.anim = new FrameAnimation(this.sprite, textures.down, 6, true);

        this.pos = tileToWorld(startTile.x, startTile.y);
        this.syncView();
    }

    /** Текущее направление взгляда (для боя: куда бьёт конус). */
    get dir(): 'down' | 'up' | 'left' | 'right' {
        return this.facing;
    }

    /** Вектор направления взгляда в мировых юнитах (экранные оси — мировые диагонали). */
    get dirVector(): Vec2 {
        switch (this.facing) {
            case 'up':
                return { x: -1, y: -1 };
            case 'left':
                return { x: -1, y: 1 };
            case 'right':
                return { x: 1, y: -1 };
            default:
                return { x: 1, y: 1 };
        }
    }

    /** Кликом по миру (юниты) выбран тайл — строим путь A* и начинаем движение.
     *  Клик за краем карты ведёт к ближайшему краевому тайлу (камера прижата границей). */
    onWorldClick(worldX: number, worldY: number): void {
        const w = this.map.data.width;
        const h = this.map.data.height;
        const clicked = worldToTile(worldX, worldY, w, h);
        const tile = clicked ?? {
            x: Math.min(w - 1, Math.max(0, Math.floor(worldX))),
            y: Math.min(h - 1, Math.max(0, Math.floor(worldY)))
        };
        const path = findPath(this.map, this.currentTile(), tile, false);
        if (path && path.length > 0) {
            this.followPath(path);
        }
    }

    /** Пойти по готовому пути тайлов (например, к краю занятого NPC/объектом тайла). */
    followPath(path: { x: number; y: number }[]): void {
        if (path.length === 0) return;
        this.path = path;
        this.advanceWaypoint();
    }

    update(dt: number): void {
        if (!this.waypoint) return;
        this.pos = moveTowardsW(this.pos, this.waypoint, this.speed * dt);
        if (this.pos.x === this.waypoint.x && this.pos.y === this.waypoint.y) {
            this.onStep?.(); // ступили на новый тайл
            this.advanceWaypoint();
            return;
        }
        this.faceMovement();
        this.anim.update(dt);
        this.syncView();
    }

    get moving(): boolean {
        return this.waypoint !== null;
    }

    /** Текущий тайл героя. */
    currentTile(): { x: number; y: number } {
        return (
            worldToTile(this.pos.x, this.pos.y, this.map.data.width, this.map.data.height) ?? { x: 0, y: 0 }
        );
    }

    /** Прямое движение (тач-джойстик/стик): экранный вектор -1..1, движение с проверкой стен. */
    moveFree(dir: Vec2, dt: number): void {
        const len = Math.hypot(dir.x, dir.y);
        if (len < 0.01) {
            this.stop();
            return;
        }
        // Экранная ось джойстика -> мировое направление (экранные оси — мировые диагонали).
        const w = screenToWorld(dir.x, dir.y);
        const n = worldNorm(w.x, w.y);
        const step = this.speed * dt;
        const nx = this.pos.x + n.x * step;
        const ny = this.pos.y + n.y * step;
        // Двигаемся только если новая точка внутри карты и не в стене
        const tile = worldToTile(nx, ny, this.map.data.width, this.map.data.height);
        if (tile && this.map.isWalkable(tile.x, tile.y)) {
            // Поворот — по экранным компонентам смещения (кадры down/up/side).
            const proj = worldToScreen(n.x, n.y);
            this.setFacing(
                Math.abs(proj.x) >= Math.abs(proj.y) ? (proj.x >= 0 ? 'right' : 'left') : proj.y >= 0 ? 'down' : 'up'
            );
            this.pos = { x: nx, y: ny };
            this.anim.update(dt);
            this.syncView();
        } else {
            this.stop();
        }
    }

    /** Позиция героя (ноги) в мировых юнитах. */
    get position(): Vec2 {
        return { x: this.pos.x, y: this.pos.y };
    }

    /** Текущий кадр спрайта (для дебага анимации). */
    get currentTexture(): Texture {
        return this.sprite.texture;
    }

    /** Прервать текущий путь (например, при уроне). */
    stop(): void {
        this.path = [];
        this.waypoint = null;
    }

    /** Мгновенно переместить героя в тайл (респаун, переходы между локациями). */
    teleportTo(tile: { x: number; y: number }): void {
        this.stop();
        this.pos = tileToWorld(tile.x, tile.y);
        this.syncView();
    }

    /** Отброс: сдвиг позиции с проверкой проходимости (для боя), юниты. */
    applyKnockback(dir: Vec2, dist: number): void {
        const nx = this.pos.x + dir.x * dist;
        const ny = this.pos.y + dir.y * dist;
        const tile = worldToTile(nx, ny, this.map.data.width, this.map.data.height);
        if (tile && this.map.isWalkable(tile.x, tile.y)) {
            this.pos = { x: nx, y: ny };
            this.syncView();
        }
        this.stop();
    }

    /** Направление — по доминирующей экранной оси движения к следующей точке пути. */
    private faceMovement(): void {
        if (!this.waypoint) return;
        const dx = this.waypoint.x - this.pos.x;
        const dy = this.waypoint.y - this.pos.y;
        const proj = worldToScreen(dx, dy);
        this.setFacing(
            Math.abs(proj.x) >= Math.abs(proj.y) ? (proj.x >= 0 ? 'right' : 'left') : proj.y >= 0 ? 'down' : 'up'
        );
    }

    /** Сменить направление взгляда (кадры + флип спрайта). */
    private setFacing(facing: Facing): void {
        if (facing === this.facing) return;
        this.facing = facing;
        const frames =
            facing === 'down' ? this.textures.down : facing === 'up' ? this.textures.up : this.textures.side;
        this.anim.setFrames([...frames], false);
        this.sprite.scale.x = facing === 'right' ? -1 : 1;
    }

    private advanceWaypoint(): void {
        const next = this.path.shift();
        this.waypoint = next ? tileToWorld(next.x, next.y) : null;
    }

    /** Вью-позиция: единственная точка перевода мир→экран (округление до px). */
    private syncView(): void {
        const s = worldToScreen(this.pos.x, this.pos.y);
        this.view.position.set(Math.round(s.x), Math.round(s.y));
    }
}

