/**
 * Soft-terrain edge blend weights and neighbor sample coords (16×16 tiles).
 *
 * One-sided (neighbor not blendable): outer 50%, inner 25%.
 * Both blendable: outer 40%, inner 20% so the shared 4-pixel strip steps
 * 20% → 40% → 60% → 80% toward the other tile instead of a flat 50/50 seam.
 * Samples use matching depth into the neighbor (not only the abutting edge).
 * Cardinal edges only — diagonals are skipped (corner L-blends read as blotches).
 */

export const SOFT_TERRAIN_EDGE_PX = 2;
export const SOFT_BLEND_OUTER = 0.5;
export const SOFT_BLEND_INNER = 0.25;
/** When the neighbor also soft-blends, ease weights so both sides form one ramp. */
export const SOFT_BLEND_OUTER_DUAL = 0.4;
export const SOFT_BLEND_INNER_DUAL = 0.2;

/**
 * Distance from the edge facing neighbor (ndx, ndy): 0 = outer pixel, 1 = one in, null = N/A.
 * Diagonal offsets always return null (not blended).
 */
export function softTerrainEdgeDepth (px, py, ndx, ndy, size = 16)
{
	const last = size - 1;
	let edgeX = null;
	let edgeY = null;
	if (ndx > 0)
	{ edgeX = last - px; }
	else if (ndx < 0)
	{ edgeX = px; }
	if (ndy > 0)
	{ edgeY = last - py; }
	else if (ndy < 0)
	{ edgeY = py; }

	if (ndx !== 0 && ndy !== 0)
	{
		// Diagonals disabled — cardinal strips alone look cleaner at corners.
		return null;
	}
	if (ndx !== 0)
	{
		if (edgeX == null || edgeX > 1)
		{ return null; }
		return edgeX;
	}
	if (ndy !== 0)
	{
		if (edgeY == null || edgeY > 1)
		{ return null; }
		return edgeY;
	}
	return null;
}

/**
 * Blend weight for pixel (px, py) toward neighbor offset (ndx, ndy).
 * @param {{ neighborBlendable?: boolean }} [options]
 */
export function softTerrainBlendWeight (px, py, ndx, ndy, size = 16, options = {})
{
	const depth = softTerrainEdgeDepth(px, py, ndx, ndy, size);
	if (depth == null)
	{ return 0; }
	const dual = !!options.neighborBlendable;
	if (depth === 0)
	{ return dual ? SOFT_BLEND_OUTER_DUAL : SOFT_BLEND_OUTER; }
	return dual ? SOFT_BLEND_INNER_DUAL : SOFT_BLEND_INNER;
}

/**
 * Neighbor sprite pixel for this blend.
 * Samples `depth` pixels into the neighbor from the abutting edge/corner
 * so inner and outer self pixels pull toward different neighbor colors.
 */
export function softTerrainNeighborSample (px, py, ndx, ndy, size = 16)
{
	const last = size - 1;
	let edgeX = null;
	let edgeY = null;
	if (ndx > 0)
	{ edgeX = last - px; }
	else if (ndx < 0)
	{ edgeX = px; }
	if (ndy > 0)
	{ edgeY = last - py; }
	else if (ndy < 0)
	{ edgeY = py; }

	const sx = ndx > 0
		? Math.max(0, Math.min(last, edgeX ?? 0))
		: (ndx < 0 ? Math.max(0, Math.min(last, last - (edgeX ?? 0))) : px);
	const sy = ndy > 0
		? Math.max(0, Math.min(last, edgeY ?? 0))
		: (ndy < 0 ? Math.max(0, Math.min(last, last - (edgeY ?? 0))) : py);
	return { sx, sy };
}

/** Cardinal neighbor offsets only (diagonals looked like corner blotches). */
export const SOFT_TERRAIN_NEIGHBOR_DIRS = Object.freeze([
	Object.freeze({ ndx: 0, ndy: -1 }),
	Object.freeze({ ndx: 1, ndy: 0 }),
	Object.freeze({ ndx: 0, ndy: 1 }),
	Object.freeze({ ndx: -1, ndy: 0 })
]);

/**
 * Mix self RGBA with weighted neighbor samples (weighted-average, then lerp by total weight).
 * @param {{ r: number, g: number, b: number, a: number }} self
 * @param {Array<{ color: { r: number, g: number, b: number, a: number }, weight: number }>} contribs
 */
export function mixSoftTerrainPixel (self, contribs)
{
	if (!contribs?.length)
	{ return self; }
	let totalW = 0;
	let r = 0;
	let g = 0;
	let b = 0;
	let a = 0;
	for (const entry of contribs)
	{
		const w = Math.max(0, entry.weight);
		if (w <= 0)
		{ continue; }
		totalW += w;
		r += entry.color.r * w;
		g += entry.color.g * w;
		b += entry.color.b * w;
		a += entry.color.a * w;
	}
	if (totalW <= 0)
	{ return self; }
	const inv = 1 / totalW;
	const avg = { r: r * inv, g: g * inv, b: b * inv, a: a * inv };
	const t = Math.min(1, totalW);
	const keep = 1 - t;
	return {
		r: Math.round(self.r * keep + avg.r * t),
		g: Math.round(self.g * keep + avg.g * t),
		b: Math.round(self.b * keep + avg.b * t),
		a: Math.round(self.a * keep + avg.a * t)
	};
}
