/**
 * VoxelRenderer — three.js как низкоуровневый рендер-бэкенд (решение v2).
 *
 * Граница рендера: мир живёт в воксельных единицах, проекция происходит
 * только здесь (урок v1 №1). Низкое разрешение бэкинг-стора + CSS-целый
 * масштаб с image-rendering: pixelated даёт пиксель-арт взгляд (продолжение
 * стиля v1). AO запечён в вершинные цвета мешером; свет — dirLight с
 * shadow map + мягкий ambient, чтобы тени не проваливались в чёрное.
 */
import * as THREE from 'three';
import type { VoxelMesh } from '../voxel/mesher';
import type { PosedVoxel } from '../animation/rig';
import type { ResolvedTile } from '../models/format';
import { lerpColor } from './daynight';
import { createSpriteLayer, createQuadLayer } from './particles';
import type { ParticleLayer } from './particles';
import { particleWindow } from './polyWindow';

/** Облако деформированных вокселей (позы рига — не выровнены по сетке). */
export interface VoxelCloud {
    /** Заменить воксели облака (позиции, цвета, тайли, rotY — количество). */
    update(voxels: readonly Pick<PosedVoxel, 'pos' | 'color' | 'tile' | 'rotY'>[]): void;
    dispose(): void;
    mesh: THREE.InstancedMesh;
}

/** Текстуры граней облака: id тайля → разрешённые hex-пиксели (см. resolveTiles). */
export type CloudTiles = Record<number, ResolvedTile>;

/** Параметры точечного источника света (окна, очаг, лампа героя). */
export interface PointLightOptions {
    /** Позиция в мировых единицах. */
    pos: [number, number, number];
    color: number;
    /** Яркость 0..~1.5 (множитель движка). */
    intensity: number;
    /** Радиус действия в мировых единицах (дальше — гаснет). */
    radius: number;
}

/** Ручка точечного источника: игра меняет яркость (мерцание) сама. */
export interface PointLightHandle {
    setIntensity(intensity: number): void;
    setPos(pos: [number, number, number]): void;
    dispose(): void;
}

export interface VoxelRendererOptions {
    /** низкое разрешение рендера (пиксель-арт), по умолчанию 480×270 */
    width?: number;
    height?: number;
    /** центр ортокамеры в мировых единицах */
    target?: [number, number, number];
    /** половина высоты орто-фрустума (зум), в мировых единицах */
    viewSize?: number;
}

/** Изометрия демо: диметрия 2:1 — yaw 45°, тангенс угла возвышения 1/2. */
export const ISO_YAW = Math.PI / 4;
const ISO_TAN = 0.5;

/** Ручка пост-прохода: юниформы (uTime и пр. — игра анимирует сама) и отключение. */
export interface PostPassHandle {
    readonly uniforms: Record<string, THREE.IUniform>;
    dispose(): void;
}

/** Вершишник полноэкранного квада пост-прохода (PlaneGeometry даёт uv). */
const POST_VERT = `
varying vec2 vUv;
void main() {
    vUv = uv;
    gl_Position = vec4(position.xy, 0.0, 1.0);
}`;

export class VoxelRenderer {
    readonly renderer: THREE.WebGLRenderer;
    readonly scene: THREE.Scene;
    readonly camera: THREE.OrthographicCamera;
    private readonly sun: THREE.DirectionalLight;
    private readonly ambient: THREE.HemisphereLight;
    private readonly target: THREE.Vector3;
    private readonly viewSize: number;
    private sunK = 0.5;
    private nightK = 0;
    /** Дневной базовый ambient области (интерьеры темнее улиц — как v1 setAmbient). */
    private dayHemisphere = 0x94949e; // P5
    /** Дневной множитель солнца (тёмный интерьер гасит и прямое солнце). */
    private daySunScale = 1;
    /** Активный пост-проход: RT со сценой + полноэкранный квад (null — прямой рендер). */
    private post: {
        rt: THREE.WebGLRenderTarget;
        scene: THREE.Scene;
        camera: THREE.OrthographicCamera;
        quad: THREE.Mesh;
        mat: THREE.ShaderMaterial;
    } | null = null;

    constructor(canvas: HTMLCanvasElement, opts: VoxelRendererOptions = {}) {
        const width = opts.width ?? 480;
        const height = opts.height ?? 270;
        this.target = new THREE.Vector3(...(opts.target ?? [0, 0, 0]));
        this.viewSize = opts.viewSize ?? 16;

        this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false });
        this.renderer.setSize(width, height, false); // CSS-размер задаёт страница
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFShadowMap;

        this.scene = new THREE.Scene();

        this.camera = this.makeCamera(width, height);

        this.ambient = new THREE.HemisphereLight(0x94949e, 0x343b2c, 0.55); // P5 / G0
        this.scene.add(this.ambient);

        this.sun = new THREE.DirectionalLight(0xffffff, 1.4);
        this.sun.castShadow = true;
        this.sun.shadow.mapSize.set(1024, 1024);
        const r = this.viewSize * 1.2;
        this.sun.shadow.camera.left = -r;
        this.sun.shadow.camera.right = r;
        this.sun.shadow.camera.top = r;
        this.sun.shadow.camera.bottom = -r;
        this.sun.shadow.bias = -0.0005;
        this.scene.add(this.sun);
        this.scene.add(this.sun.target);
        this.setSun(0.5);
        this.repositionCamera();
    }

    /** Перенести цель камеры (и солнце за ней) — слежение камеры за героем. */
    setTarget(t: readonly [number, number, number]): void {
        this.target.set(t[0], t[1], t[2]);
        this.repositionCamera();
        this.setSun(this.sunK);
    }

    /** Текущая цель камеры (для моста/гейта). */
    currentTarget(): [number, number, number] {
        return [this.target.x, this.target.y, this.target.z];
    }

    /**
     * Дневной базовый тон области: цвет неба hemisphere днём (улицы — P5,
     * тёмные интерьеры — их ambient) + дневной множитель солнца по яркости
     * (аналог multiply-ambient v1: тёмная лавка гасит и прямое солнце).
     */
    setDayAmbient(color: number): void {
        this.dayHemisphere = color & 0xffffff;
        const r = (color >> 16) & 0xff;
        const g = (color >> 8) & 0xff;
        const b = color & 0xff;
        const lum = (r * 0.3 + g * 0.6 + b * 0.1) / 255;
        this.daySunScale = Math.min(1, Math.max(0, lum * 1.6));
    }

    /**
     * Ночь: k — фактор ночи 0..1 (кривая суток игры), tint — целевой
     * ambient-цвет области (микс день/закат/ночь, кривая dayNightAmbient).
     * Гасит солнце и сдвигает дневное небо hemisphere к tint; фон сцены — tint.
     */
    setNight(k: number, tint: number): void {
        this.nightK = Math.min(1, Math.max(0, k));
        this.ambient.color.set(lerpColor(this.dayHemisphere, tint & 0xffffff, this.nightK));
        this.setSun(this.sunK); // солнце пересчитает себя с учётом nightK
        if (!this.scene.background) this.scene.background = new THREE.Color();
        (this.scene.background as THREE.Color).set(tint & 0xffffff);
    }

    /** Точечный источник (не бросает тень): мерцание — через setIntensity. */
    addPointLight(opts: PointLightOptions): PointLightHandle {
        const light = new THREE.PointLight(opts.color, opts.intensity, opts.radius * 2, 1.6);
        light.position.set(...opts.pos);
        this.scene.add(light);
        return {
            setIntensity: (i) => {
                light.intensity = i;
            },
            setPos: (p) => {
                light.position.set(p[0], p[1], p[2]);
            },
            dispose: () => {
                this.scene.remove(light);
                light.dispose();
            },
        };
    }

    /** Материал вокселей: вершинные цвета (палитра × AO) + ламберт от солнца. */
    static material(): THREE.MeshLambertMaterial {
        return new THREE.MeshLambertMaterial({ vertexColors: true });
    }

    /** Добавляет меш из MeshData мешера в сцену (тени: cast + receive). */
    addMesh(mesh: VoxelMesh): THREE.Mesh {
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(mesh.positions, 3));
        geo.setAttribute('normal', new THREE.Float32BufferAttribute(mesh.normals, 3));
        geo.setAttribute('color', new THREE.Float32BufferAttribute(mesh.colors, 3));
        geo.setIndex(mesh.indices);
        const meshObj = new THREE.Mesh(geo, VoxelRenderer.material());
        meshObj.castShadow = true;
        meshObj.receiveShadow = true;
        this.scene.add(meshObj);
        return meshObj;
    }

    /**
     * Облако вокселей для поз анимации: instanced кубы 1×1×1 (ось-выровнены),
     * позиция и цвет — на инстанс. Обновление позы — без пересборки геометрии.
     * tiles — текстуры граней (см. resolveTiles): воксель с tile>0 рисуется
     * пиксель-артом тайля (цвет инстанса — белый), без tile — плоским цветом.
     */
    addVoxelCloud(voxels: readonly Pick<PosedVoxel, 'pos' | 'color' | 'tile' | 'rotY'>[], tiles?: CloudTiles): VoxelCloud {
        return createCloud(this.scene, voxels, tiles);
    }

    /**
     * Слой частиц-спрайтов (билборды, лицом к камере): пепел, мотыльки.
     * Размер частицы — в мировых юнитах, переводится в пиксели буфера один
     * раз (канвас рендера не меняется после создания).
     */
    addParticles(): ParticleLayer {
        const px = this.renderer.domElement.height / (2 * this.viewSize);
        return createSpriteLayer(this.scene, 64, px);
    }

    /** Слой плоских квадов, лежащих на земле/воде: дымка прудов, блики. */
    addFlatParticles(): ParticleLayer {
        return createQuadLayer(this.scene, 64);
    }

    /**
     * Окно видимости частиц: AABB орто-фрустума, пересечённого с горизон-
     * тальным слоем [y0,y1], вокруг цели камеры. Точка вне окна заведомо не
     * проецируется на экран — там частицы заворачивают/респавнятся без
     * «появления из воздуха». Окно заметно шире наземного следа кадра:
     * высокую частицу видно дальше от цели, а сляб уходит в глубину до
     * дальней плоскости (точно — для частиц много ниже камеры, как все
     * игровые слои).
     */
    visibleWindow(y0: number, y1: number): { minX: number; maxX: number; minZ: number; maxZ: number } {
        // БЕЗ кэша: окно обязано ехать за камерой (грабля — кэш от первого
        // запроса замирал на окне вокруг origin, частицы получали alpha 0)
        this.camera.updateMatrixWorld();
        const e = this.camera.matrixWorld.elements;
        // базис камеры: r — экранная горизонталь, u — вертикаль, f — взгляд
        const r = [e[0]!, e[1]!, e[2]!] as const;
        const u = [e[4]!, e[5]!, e[6]!] as const;
        const f = [-e[8]!, -e[9]!, -e[10]!] as const;
        const c = this.camera.position;
        const t = this.target;
        // глубина цели вдоль взгляда: ближняя/дальняя плоскости относительно неё
        const D = f[0] * (t.x - c.x) + f[1] * (t.y - c.y) + f[2] * (t.z - c.z);
        const box = particleWindow({
            r, u, f,
            a: this.camera.right, h: this.camera.top,
            k0: this.camera.near - D, k1: this.camera.far - D,
            dy0: y0 - t.y, dy1: y1 - t.y,
        });
        // AABB посчитан в дельтах от цели камеры — переводим в мировые координаты
        return {
            minX: box.minX + t.x, maxX: box.maxX + t.x,
            minZ: box.minZ + t.z, maxZ: box.maxZ + t.z,
        };
    }

    /**
     * Солнце дня: k — 0 рассвет → 0.5 полдень → 1 закат. Азимут едет по
     * мировой горизонтали (восток→запад), высота — по синусу дня; цвет теплеет
     * у горизонта. Тени на земле ползут от k — это ловит скриншот-гейт.
     */
    setSun(k: number): void {
        this.sunK = k;
        const kk = Math.min(1, Math.max(0, k));
        const az = Math.PI * (1 - kk); // 180°→0°: восток → юг → запад
        const elev = Math.sin(kk * Math.PI) * (Math.PI / 3) + 0.12; // не ниже ~7°
        const dist = this.viewSize * 3;
        this.sun.position.set(
            this.target.x + dist * Math.cos(az) * Math.cos(elev),
            this.target.y + dist * Math.sin(elev),
            this.target.z + dist * Math.sin(az) * Math.cos(elev),
        );
        this.sun.target.position.copy(this.target);
        // ночь гасит солнце до остаточной засветки (луна/небо), тёмный интерьер — и днём
        this.sun.intensity =
            (0.4 + 1.1 * Math.sin(kk * Math.PI)) * (1 - 0.92 * this.nightK) * this.daySunScale;
        // тёплый свет у горизонта (F1), нейтральный в полдень
        const warm = 1 - Math.sin(kk * Math.PI);
        this.sun.color.setRGB(1, 1 - warm * 0.25, 1 - warm * 0.45);
    }

    /**
     * Пост-обработка: сцена рендерится в render target, затем на экран
     * полноэкранным квадом с шейдером игры (виньетка, дисторсия...).
     * null — вернуться к прямому рендеру. Юниформы прохода игрок меняет
     * через ручку (uTime и пр.). Ресурсов мало, но dispose обязателен.
     */
    setPostPass(
        fragmentShader: string | null,
        uniforms: Record<string, THREE.IUniform> = {},
    ): PostPassHandle | null {
        this.clearPostPass();
        if (fragmentShader === null) return null;
        const size = new THREE.Vector2();
        this.renderer.getSize(size);
        const rt = new THREE.WebGLRenderTarget(size.x, size.y, {
            minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, // пиксель-арт: 1:1
        });
        const mat = new THREE.ShaderMaterial({
            vertexShader: POST_VERT,
            fragmentShader,
            // uTime заводится всегда (пост-шейдер собирается с его объявлением),
            // эффектные юниформы — из spec'а игры
            uniforms: { tDiffuse: { value: rt.texture }, uTime: { value: 0 }, ...uniforms },
            depthTest: false,
            depthWrite: false,
        });
        const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
        quad.frustumCulled = false;
        const scene = new THREE.Scene();
        scene.add(quad);
        const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
        this.post = { rt, scene, camera, quad, mat };
        return {
            uniforms: mat.uniforms,
            dispose: () => this.clearPostPass(),
        };
    }

    /** Снять активный пост-проход и освободить его ресурсы. */
    private clearPostPass(): void {
        const p = this.post;
        if (!p) return;
        this.post = null;
        p.scene.remove(p.quad);
        p.quad.geometry.dispose();
        p.mat.dispose();
        p.rt.dispose();
    }

    /** Один кадр. */
    render(): void {
        this.camera.updateMatrixWorld();
        if (this.post) {
            this.renderer.setRenderTarget(this.post.rt);
            this.renderer.render(this.scene, this.camera);
            this.renderer.setRenderTarget(null);
            this.renderer.render(this.post.scene, this.post.camera);
        } else {
            this.renderer.render(this.scene, this.camera);
        }
    }

    /** Ортокамера диметрии 2:1, смотрит в target с изо-направления. */
    private makeCamera(width: number, height: number): THREE.OrthographicCamera {
        const aspect = width / height;
        const half = this.viewSize;
        return new THREE.OrthographicCamera(
            -half * aspect, half * aspect, half, -half, 0.1, this.viewSize * 10,
        );
    }

    /** Поставить камеру в изо-направление от текущего target. */
    private repositionCamera(): void {
        const dir = new THREE.Vector3(
            Math.cos(ISO_YAW) * ISO_TAN,
            1, // камера НАД сценой (минус давал вид из-под земли: верхние грани без света)
            Math.sin(ISO_YAW) * ISO_TAN,
        ).normalize();
        this.camera.position.copy(this.target).addScaledVector(dir, this.viewSize * 4);
        this.camera.lookAt(this.target);
    }
}

/**
 * Атлас тайлей: одна строка, ячейка тайля = 6 суб-граней подряд
 * (+x,−x,+y,−y,+z,−z), ячейка 0 — белая (плоский цвет × instanceColor).
 * Канвас рисуется сверху-вниз, flipY=true у CanvasTexture ставит низ канваса
 * на v=0 — низ грани сэмплирует низ арта, текстура читается естественно.
 */
function buildTileAtlas(tiles: CloudTiles): { texture: THREE.CanvasTexture; texel: number; width: number } {
    let texel = 1, maxId = 0;
    for (const [id, t] of Object.entries(tiles)) {
        texel = Math.max(texel, t.size);
        maxId = Math.max(maxId, Number(id));
    }
    const width = (maxId + 1) * 6 * texel;
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = texel;
    const ctx = canvas.getContext('2d')!;
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, 6 * texel, texel);
    for (const [id, t] of Object.entries(tiles)) {
        const k = texel / t.size; // тайли мельче texel растягиваются в ячейку
        const hexToCss = (hex: string) => (hex.length === 4 ? '#' + [...hex.slice(1)].map((c) => c + c).join('') : hex);
        t.faces.forEach((pixels, fi) => {
            pixels.forEach((hex, px) => {
                ctx.fillStyle = hexToCss(hex);
                ctx.fillRect((Number(id) * 6 + fi) * texel + (px % t.size) * k, Math.floor(px / t.size) * k, k, k);
            });
        });
    }
    const texture = new THREE.CanvasTexture(canvas);
    texture.magFilter = THREE.NearestFilter;
    texture.minFilter = THREE.NearestFilter;
    texture.generateMipmaps = false;
    texture.colorSpace = THREE.SRGBColorSpace;
    return { texture, texel, width };
}

/** Шейдерная инъция: uv сэмплинга атласа по грани куба (индекс из нормали).
 *  Общая для облака (aTileId — инстансный атрибут) и world-меша (обычный
 *  атрибут из мешера + uv) — объявление атрибута одинаково. */
function texturizeAtlasMaterial(mat: THREE.MeshLambertMaterial, texel: number, width: number): void {
    mat.onBeforeCompile = (shader) => {
        shader.uniforms.uTexel = { value: texel };
        shader.uniforms.uAtlasWidth = { value: width };
        shader.vertexShader = shader.vertexShader
            .replace('#include <common>', '#include <common>\nattribute float aTileId;\nvarying float vTile;\nvarying float vFace;')
            .replace('#include <begin_vertex>', [
                '#include <begin_vertex>',
                'vTile = aTileId;',
                'vFace = normal.x > 0.5 ? 0.0 : normal.x < -0.5 ? 1.0 : normal.y > 0.5 ? 2.0 : normal.y < -0.5 ? 3.0 : normal.z > 0.5 ? 4.0 : 5.0;',
            ].join('\n'));
        shader.fragmentShader = shader.fragmentShader
            .replace('#include <common>', '#include <common>\nvarying float vTile;\nvarying float vFace;\nuniform float uTexel;\nuniform float uAtlasWidth;')
            .replace('#include <map_fragment>', [
                '#ifdef USE_MAP',
                'vec2 cell = vec2((vTile * 6.0 + vFace) + vMapUv.x, vMapUv.y) * uTexel;',
                'diffuseColor *= texture2D(map, cell / vec2(uAtlasWidth, uTexel));',
                '#endif',
            ].join('\n'));
    };
}

/**
 * Общий атлас тайлей мира: один texture на все чанки области (материалы
 * чанков сэмплируют его через applyTo; texture дисползится ТОЛЬКО через
 * dispose владельца — не из материала отдельного чанка).
 */
export interface WorldTileAtlas {
    readonly texture: THREE.CanvasTexture;
    /** Подключить атлас к материалу чанка (шейдерная инъция сэмплинга). */
    applyTo(mat: THREE.MeshLambertMaterial): void;
    dispose(): void;
}

/**
 * Атлас реестра тайлей мира: мешер даёт per-vertex tiles/uvs (атрибуты
 * aTileId и uv у BufferGeometry), сэмплинг — общий с облаком. Пустой
 * реестр — null (материалы чанков остаются плоско-цветными).
 */
export function worldTileAtlas(tiles: CloudTiles): WorldTileAtlas | null {
    if (!tiles || Object.keys(tiles).length === 0) return null;
    const atlas = buildTileAtlas(tiles);
    return {
        texture: atlas.texture,
        applyTo: (mat) => {
            mat.map = atlas.texture;
            texturizeAtlasMaterial(mat, atlas.texel, atlas.width);
        },
        dispose: () => atlas.texture.dispose(),
    };
}

/** Фабрика облака (отдельная функция — рекурсия при росте ёмкости). */
function createCloud(
    scene: THREE.Scene,
    voxels: readonly Pick<PosedVoxel, 'pos' | 'color' | 'tile' | 'rotY'>[],
    tiles?: CloudTiles,
): VoxelCloud {
    const textured = !!tiles && Object.keys(tiles).length > 0;
    const geo = new THREE.BoxGeometry(1, 1, 1);
    const mat = new THREE.MeshLambertMaterial();
    let atlas: { texture: THREE.CanvasTexture; texel: number; width: number } | null = null;
    if (textured) {
        atlas = buildTileAtlas(tiles!);
        mat.map = atlas.texture;
        texturizeAtlasMaterial(mat, atlas.texel, atlas.width);
    }
    const mesh = new THREE.InstancedMesh(geo, mat, Math.max(1, voxels.length));
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    mesh.frustumCulled = false; // bbox у InstancedMesh не считается по инстансам
    const tileAttr = new THREE.InstancedBufferAttribute(new Float32Array(mesh.instanceMatrix.count), 1);
    tileAttr.setUsage(THREE.DynamicDrawUsage);
    geo.setAttribute('aTileId', tileAttr);
    scene.add(mesh);

    const cloud: VoxelCloud = {
        mesh,
        update: (list) => {
            if (list.length > mesh.instanceMatrix.count) {
                scene.remove(mesh);
                geo.dispose();
                mat.dispose();
                atlas?.texture.dispose();
                const fresh = createCloud(scene, list, tiles);
                cloud.update = fresh.update;
                cloud.dispose = fresh.dispose;
                cloud.mesh = fresh.mesh;
                return;
            }
            const m = new THREE.Matrix4();
            const c = new THREE.Color();
            list.forEach((v, i) => {
                // куб поворачивается вместе с моделью (rotY), иначе на
                // диагональном ходе оси-выровненные кубы «пилят» углами
                m.makeRotationY(v.rotY ?? 0);
                mesh.setMatrixAt(i, m.setPosition(v.pos[0], v.pos[1], v.pos[2]));
                mesh.setColorAt(i, c.set(v.tile ? '#ffffff' : v.color));
                tileAttr.array[i] = v.tile ?? 0;
            });
            mesh.count = list.length;
            mesh.instanceMatrix.needsUpdate = true;
            if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
            tileAttr.needsUpdate = true;
        },
        dispose: () => {
            scene.remove(mesh);
            geo.dispose();
            mat.dispose();
            atlas?.texture.dispose();
        },
    };
    cloud.update(voxels);
    return cloud;
}