export const CHART_COLORS = [
    '#71B6D3',
    '#70F8BA',
    '#FFCD56',
    '#6B7FD7',
    '#F4A261',
    '#AA6DA3',
    '#F45B69',
    '#4ECDC4',
    '#BF98A0',
    '#9A8C98',
    '#C9A227',
    '#E6AACE',
];

/** Starting palette index per chart scope so widgets don't all open on the same hue. */
const SCOPE_COLOR_OFFSETS = {
    channels: 3,
    browsers: 0,
    devices: 6,
    operating_systems: 9,
};

/** @type {Record<string, Record<string, string>>} */
const labelColorMaps = {};

/**
 * @param {string} scope
 * @return {number}
 */
function getScopeColorOffset(scope = 'default') {
    return SCOPE_COLOR_OFFSETS[scope] ?? 0;
}

/**
 * Full palette rotated so the first slot matches the chart scope offset.
 *
 * @param {string} scope
 * @return {string[]}
 */
export function getChartColorsForScope(scope = 'default') {
    const offset = getScopeColorOffset(scope);
    return CHART_COLORS.map((_, index) => CHART_COLORS[(offset + index) % CHART_COLORS.length]);
}

/**
 * Stable colors from the palette: first time a label appears (per scope), it gets the next color.
 * Matches fresh-page order (blue, green, yellow, …) instead of hash-assigned slots.
 *
 * @param {string[]} labels  Chart segment labels.
 * @param {string}   scope   e.g. browsers, devices, channels — separate maps per chart tab.
 * @return {string[]}
 */
export function getColorsForLabels(labels, scope = 'default') {
    if (!labelColorMaps[scope]) {
        labelColorMaps[scope] = {};
    }

    const map = labelColorMaps[scope];
    const offset = getScopeColorOffset(scope);
    let nextColorIndex = offset + Object.keys(map).length;

    labels.forEach((label) => {
        if (!map[label]) {
            map[label] = CHART_COLORS[nextColorIndex % CHART_COLORS.length];
            nextColorIndex += 1;
        }
    });

    const fallbackIndex = offset % CHART_COLORS.length;
    return labels.map((label) => map[label] || CHART_COLORS[fallbackIndex]);
}
