export default function normalizeToSegments(states, layout) {
  if (!layout) {
    return undefined;
  }
  const totalSegments = layout[0] * layout[1];
  let totalPortionCount = 0;
  const minimumPortion = 1;
  const stateEntries = Object.entries(states);

  // Step 1: Assign at least one portion to each state
  const initialSegments = stateEntries.map(([fips, popPct]) => {
    const exactPortionCount = popPct * (totalSegments - stateEntries.length); // Allocate from remaining segments
    const portionCount = Math.floor(exactPortionCount) + minimumPortion;
    const fractionalPart = exactPortionCount - Math.floor(exactPortionCount);
    totalPortionCount += portionCount;
    return {
      fips,
      portionCount,
      fractionalPart
    };
  });

  // Step 2: Distribute any leftover segments based on highest fractional part
  const leftoverSegments = totalSegments - totalPortionCount;
  if (leftoverSegments > 0) {
    // Sort states by fractional part in descending order
    initialSegments.sort((a, b) => b.fractionalPart - a.fractionalPart);
    initialSegments.slice(0, leftoverSegments)
    // eslint-disable-next-line no-param-reassign
    .forEach(segment => {
      segment.portionCount += 1;
    });
  }

  // Step 3: Return the states with the final portion counts
  return initialSegments;
}