import { setPixel } from './pixelEditorUtils.js';

/**
 * spriteGeneratorCore.ts — Core generator engine for assembling pixel art
 * sprites from modular parts (heads, torsos, limbs, accessories).
 *
 * Supports: characters, animals, buildings with skeleton integration,
 * 8-directional rendering, and 2.5D isometric projection.
 */
const ALL_DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
/* ════════════════════════════════════════════════════════════════
   PART PIXEL DATA HELPERS
   ════════════════════════════════════════════════════════════════ */
/** Create PartPixelData from a compact row array */
function createPartData(width, height, rows, palette) {
    var _a;
    const data = [];
    for (let y = 0; y < height; y++) {
        const row = rows[y] || [];
        for (let x = 0; x < width; x++) {
            data.push((_a = row[x]) !== null && _a !== void 0 ? _a : -1);
        }
    }
    return { width, height, data, palette };
}
/** Mirror part data horizontally */
function mirrorPartH(part) {
    const { width, height, data, palette } = part;
    const mirrored = new Array(data.length);
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            mirrored[y * width + x] = data[y * width + (width - 1 - x)];
        }
    }
    return { width, height, data: mirrored, palette };
}
/** Generate mirrored directions from existing ones */
function generateMirroredDirections(pixels) {
    const result = { ...pixels };
    const mirrorPairs = [
        ['E', 'W'], ['NE', 'NW'], ['SE', 'SW'],
    ];
    for (const [from, to] of mirrorPairs) {
        if (result[from] && !result[to]) {
            result[to] = mirrorPartH(result[from]);
        }
        else if (result[to] && !result[from]) {
            result[from] = mirrorPartH(result[to]);
        }
    }
    return result;
}
/* ════════════════════════════════════════════════════════════════
   RENDERING ENGINE
   ════════════════════════════════════════════════════════════════ */
function hexToRgba(hex) {
    const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
    if (!m)
        return [0, 0, 0, 255];
    return [
        parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16),
        m[4] ? parseInt(m[4], 16) : 255,
    ];
}
/** Render a single part onto an ImageData */
function renderPart(target, part, direction, offsetX, offsetY, colorOverrides, flipH = false) {
    var _a;
    const pixelData = part.pixels[direction] || part.pixels.S;
    if (!pixelData)
        return;
    const { width, height, data, palette } = pixelData;
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            const idx = data[y * width + x];
            if (idx < 0)
                continue;
            const colorHex = (_a = colorOverrides === null || colorOverrides === void 0 ? void 0 : colorOverrides[idx]) !== null && _a !== void 0 ? _a : palette[idx];
            if (!colorHex)
                continue;
            const color = hexToRgba(colorHex);
            const px = flipH ? (offsetX + width - 1 - x) : (offsetX + x);
            const py = offsetY + y;
            if (px >= 0 && px < target.width && py >= 0 && py < target.height) {
                setPixel(target, px, py, color);
            }
        }
    }
}
/** Assemble all parts into a single frame */
function assembleSprite(assembly, parts, direction = 'S') {
    const img = new ImageData(assembly.canvasWidth, assembly.canvasHeight);
    // Sort by z-order
    const sorted = [...assembly.parts]
        .filter(ap => ap.visible !== false)
        .sort((a, b) => {
        var _a, _b;
        const partA = parts.get(a.partId);
        const partB = parts.get(b.partId);
        return ((_a = partA === null || partA === void 0 ? void 0 : partA.zOrder) !== null && _a !== void 0 ? _a : 0) - ((_b = partB === null || partB === void 0 ? void 0 : partB.zOrder) !== null && _b !== void 0 ? _b : 0);
    });
    for (const ap of sorted) {
        const part = parts.get(ap.partId);
        if (!part)
            continue;
        renderPart(img, part, direction, ap.offsetX, ap.offsetY, ap.colorOverrides, ap.flipH);
    }
    return img;
}
/** Generate all 8 directions for an assembly */
function generateAllDirections(assembly, parts, directions = ALL_DIRECTIONS) {
    const result = new Map();
    for (const dir of directions) {
        result.set(dir, assembleSprite(assembly, parts, dir));
    }
    return result;
}
/* ════════════════════════════════════════════════════════════════
   2.5D ISOMETRIC PROJECTION
   ════════════════════════════════════════════════════════════════ */
/** Apply 2.5D isometric transformation to an ImageData */
function applyIsometricProjection(source, tiltAngle = 30) {
    const rads = (tiltAngle * Math.PI) / 180;
    const cosA = Math.cos(rads);
    const sinA = Math.sin(rads);
    const sw = source.width;
    const sh = source.height;
    // Output dimensions: wider and shorter
    const dw = Math.ceil(sw * 1.5);
    const dh = Math.ceil(sh * cosA + sw * sinA * 0.5);
    const result = new ImageData(dw, dh);
    const cx = sw / 2;
    const cy = sh;
    const dx = dw / 2;
    const dy = dh;
    for (let sy = 0; sy < sh; sy++) {
        for (let sx = 0; sx < sw; sx++) {
            const si = (sy * sw + sx) * 4;
            if (source.data[si + 3] === 0)
                continue;
            // Isometric transform
            const rx = sx - cx;
            const ry = sy - cy;
            const isoX = Math.round(dx + rx - ry * sinA * 0.5);
            const isoY = Math.round(dy + ry * cosA);
            if (isoX >= 0 && isoX < dw && isoY >= 0 && isoY < dh) {
                const di = (isoY * dw + isoX) * 4;
                result.data[di] = source.data[si];
                result.data[di + 1] = source.data[si + 1];
                result.data[di + 2] = source.data[si + 2];
                result.data[di + 3] = source.data[si + 3];
            }
        }
    }
    return result;
}
/** Render 8-direction sprite sheet (all directions in a strip) */
function render8DirSpriteSheet(frames, columns = 8) {
    const dirs = ALL_DIRECTIONS;
    const firstFrame = frames.get('S') || frames.values().next().value;
    if (!firstFrame)
        return new ImageData(1, 1);
    const fw = firstFrame.width;
    const fh = firstFrame.height;
    const rows = Math.ceil(dirs.length / columns);
    const sheet = new ImageData(fw * columns, fh * rows);
    let col = 0;
    let row = 0;
    for (const dir of dirs) {
        const frame = frames.get(dir);
        if (frame) {
            for (let y = 0; y < fh; y++) {
                for (let x = 0; x < fw; x++) {
                    const si = (y * fw + x) * 4;
                    const dx = col * fw + x;
                    const dy = row * fh + y;
                    const di = (dy * sheet.width + dx) * 4;
                    sheet.data[di] = frame.data[si];
                    sheet.data[di + 1] = frame.data[si + 1];
                    sheet.data[di + 2] = frame.data[si + 2];
                    sheet.data[di + 3] = frame.data[si + 3];
                }
            }
        }
        col++;
        if (col >= columns) {
            col = 0;
            row++;
        }
    }
    return sheet;
}
/* ════════════════════════════════════════════════════════════════
   RECOLOR SYSTEM
   ════════════════════════════════════════════════════════════════ */
/** Shift hue of a hex color */
function shiftHue(hex, degrees) {
    const rgba = hexToRgba(hex);
    const [r, g, b] = rgba;
    // RGB → HSL
    const rf = r / 255, gf = g / 255, bf = b / 255;
    const max = Math.max(rf, gf, bf), min = Math.min(rf, gf, bf);
    const l = (max + min) / 2;
    let h = 0, s = 0;
    if (max !== min) {
        const d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        if (max === rf)
            h = ((gf - bf) / d + (gf < bf ? 6 : 0)) / 6;
        else if (max === gf)
            h = ((bf - rf) / d + 2) / 6;
        else
            h = ((rf - gf) / d + 4) / 6;
    }
    // Shift hue
    h = ((h * 360 + degrees) % 360) / 360;
    if (h < 0)
        h += 1;
    // HSL → RGB
    const hue2rgb = (p, q, t) => {
        if (t < 0)
            t += 1;
        if (t > 1)
            t -= 1;
        if (t < 1 / 6)
            return p + (q - p) * 6 * t;
        if (t < 1 / 2)
            return q;
        if (t < 2 / 3)
            return p + (q - p) * (2 / 3 - t) * 6;
        return p;
    };
    let nr, ng, nb;
    if (s === 0) {
        nr = ng = nb = l;
    }
    else {
        const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        const p = 2 * l - q;
        nr = hue2rgb(p, q, h + 1 / 3);
        ng = hue2rgb(p, q, h);
        nb = hue2rgb(p, q, h - 1 / 3);
    }
    const toH = (n) => Math.round(n * 255).toString(16).padStart(2, '0');
    return `#${toH(nr)}${toH(ng)}${toH(nb)}`;
}
/** Generate recolor map from a base palette */
function generateRecolorMap(basePalette, hueShift, saturationScale = 1, lightnessShift = 0) {
    const map = {};
    for (let i = 0; i < basePalette.length; i++) {
        map[i] = shiftHue(basePalette[i], hueShift);
    }
    return map;
}
/* ════════════════════════════════════════════════════════════════
   PART REGISTRY
   ════════════════════════════════════════════════════════════════ */
const _partRegistry = new Map();
function registerPart(part) {
    _partRegistry.set(part.id, part);
}
function getPart(id) {
    return _partRegistry.get(id);
}
function getPartsByCategory(category) {
    return [..._partRegistry.values()].filter(p => p.category === category);
}
function getPartsBySlot(slot) {
    return [..._partRegistry.values()].filter(p => p.slot === slot);
}
function getAllParts() {
    return [..._partRegistry.values()];
}
function registerParts(parts) {
    for (const p of parts)
        registerPart(p);
}

export { ALL_DIRECTIONS, applyIsometricProjection, assembleSprite, createPartData, generateAllDirections, generateMirroredDirections, generateRecolorMap, getAllParts, getPart, getPartsByCategory, getPartsBySlot, mirrorPartH, registerPart, registerParts, render8DirSpriteSheet, renderPart, shiftHue };
//# sourceMappingURL=spriteGeneratorCore.js.map
