export const MAX_INDENT_LEVEL = 6;

const toRoman = (num) => {
  if (num <= 0) return '';
  const lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
  let roman = '', i;
  for ( i in lookup ) {
    while ( num >= lookup[i] ) {
      roman += i;
      num -= lookup[i];
    }
  }
  return roman;
};

const toAlpha = (num) => {
  if (num <= 0) return '';
  // 1=a, 26=z, 27=aa... simplifying for standard outlines which rarely go beyond z
  return String.fromCharCode(96 + ((num - 1) % 26) + 1); 
};

const toRomanLower = (num) => toRoman(num).toLowerCase();

export const validateIndentLevel = (level) => {
  return Math.max(0, Math.min(level, MAX_INDENT_LEVEL));
};

export const getIndentSpacing = (level) => {
  return level * 24; // 24px per level matches the BulletPointEditor default
};

export const getIndentMarker = (level, count) => {
  // count is 1-based index among siblings
  switch(level) {
    case 0: return `${count}.`;         // 1.
    case 1: return `${toAlpha(count)}.`; // a.
    case 2: return `${toRomanLower(count)}.`; // i.
    case 3: return `(${count})`;        // (1)
    case 4: return `(${toAlpha(count)})`; // (a)
    case 5: return `(${toRomanLower(count)})`; // (i)
    case 6: return `-`;                 // -
    default: return `-`;
  }
};

export const getIndentLabel = (level) => {
    switch(level) {
        case 0: return "Level 1 (Number)";
        case 1: return "Level 2 (Letter)";
        case 2: return "Level 3 (Roman)";
        case 3: return "Level 4 (Number)";
        case 4: return "Level 5 (Letter)";
        case 5: return "Level 6 (Roman)";
        case 6: return "Level 7 (Dash)";
        default: return `Level ${level + 1}`;
    }
};

// Helper to count siblings for a specific item index in a flat list with levels
export const calculateSiblingCount = (items, currentIndex, levelKey = 'level') => {
    const currentItem = items[currentIndex];
    const currentLevel = currentItem[levelKey];
    
    // Find the start boundary (parent or start of list)
    let startIndex = -1;
    for (let i = currentIndex - 1; i >= 0; i--) {
        if (items[i][levelKey] < currentLevel) {
            startIndex = i;
            break;
        }
    }

    // Count siblings between start boundary and current index
    let count = 0;
    for (let i = startIndex + 1; i <= currentIndex; i++) {
        if (items[i][levelKey] === currentLevel) {
            count++;
        }
    }
    return count;
};