import React, { useMemo } from "react";
import { __ } from "@wordpress/i18n";

const SEGMENT_COLORS = [
	"#2e9e4f",
	"#2271b1",
	"#d63638",
	"#dba617",
	"#7c3aed",
	"#0e7490",
	"#b45309",
	"#4d7c0f",
	"#be185d",
	"#334155",
	"#0f766e",
];

export const rangeColor = (index) => SEGMENT_COLORS[index % SEGMENT_COLORS.length];

/**
 * Multi-thumb range partition slider (generalization of the Flexible
 * Renewal Sync segment slider): N boundary points split [0, scaleMax] into
 * N+1 ranges. Overlaid native range inputs — track ignores pointer events,
 * thumbs re-enable them — with JS clamping between neighbors.
 */
const RangeSlider = ({ boundaries, onChange, scaleMax, isCount, currencySymbol }) => {
	const format = (value) =>
		isCount ? String(Math.round(value)) : `${currencySymbol}${Number(value).toFixed(2).replace(/\.00$/, "")}`;

	const gradient = useMemo(() => {
		if (boundaries.length === 0) {
			return rangeColor(0);
		}
		const stops = [];
		let previous = 0;
		boundaries.forEach((boundary, index) => {
			const pct = Math.min(100, (boundary / scaleMax) * 100);
			stops.push(`${rangeColor(index)} ${previous}% ${pct}%`);
			previous = pct;
		});
		stops.push(`${rangeColor(boundaries.length)} ${previous}% 100%`);
		return `linear-gradient(to right, ${stops.join(", ")})`;
	}, [boundaries, scaleMax]);

	const clamp = (index, rawValue) => {
		const step = isCount ? 1 : Math.max(scaleMax / 1000, 0.01);
		const lower = index > 0 ? boundaries[index - 1] + step : step;
		const upper = index < boundaries.length - 1 ? boundaries[index + 1] - step : scaleMax;
		let value = Math.min(Math.max(rawValue, lower), Math.max(lower, upper));
		if (isCount) {
			value = Math.round(value);
		} else {
			value = Math.round(value * 100) / 100;
		}
		return value;
	};

	const handleInput = (index, rawValue) => {
		const value = clamp(index, Number(rawValue));
		const next = [...boundaries];
		next[index] = value;
		onChange(next);
	};

	return (
		<div className="arraysubs-box-range-slider">
			<div className="arraysubs-box-range-slider__bar" style={{ background: gradient }}>
				{boundaries.map((boundary, index) => (
					<React.Fragment key={index /* eslint-disable-line react/no-array-index-key */}>
						<input
							type="range"
							className="arraysubs-box-range-slider__input"
							min={0}
							max={scaleMax}
							step={isCount ? 1 : Math.max(scaleMax / 1000, 0.01)}
							value={boundary}
							onChange={(event) => handleInput(index, event.target.value)}
							aria-label={`${__("Range point", "arraysubs")} ${index + 1}`}
						/>
						<span
							className="arraysubs-box-range-slider__bubble"
							style={{
								left: `calc(${Math.min(100, (boundary / scaleMax) * 100)}% - ${
									(Math.min(100, (boundary / scaleMax) * 100) / 100) * 18 - 9
								}px)`,
							}}
						>
							{format(boundary)}
						</span>
					</React.Fragment>
				))}
			</div>
			<div className="arraysubs-box-range-slider__scale">
				<span>{format(0)}</span>
				<span>{format(scaleMax)}</span>
			</div>
		</div>
	);
};

export default RangeSlider;
