export const PWD_DIGIT = 'pwd-digit';
export const PWD_SYMBOL = 'pwd-symbol';
export const PWD_LETTER = 'pwd-letter';

type Class = typeof PWD_DIGIT | typeof PWD_SYMBOL | typeof PWD_LETTER;

function classify(ch: string): Class {
  if (/^\d$/.test(ch)) return PWD_DIGIT;
  if (/^\p{L}$/u.test(ch)) return PWD_LETTER;
  return PWD_SYMBOL;
}

export function colorizePassword(text: string): DocumentFragment {
  const frag = document.createDocumentFragment();
  if (text.length === 0) return frag;

  const codepoints = Array.from(text);
  let runStart = 0;
  let runClass = classify(codepoints[0]);

  for (let i = 1; i <= codepoints.length; i++) {
    const c = i < codepoints.length ? classify(codepoints[i]) : null;
    if (c !== runClass) {
      const span = document.createElement('span');
      span.className = runClass;
      span.textContent = codepoints.slice(runStart, i).join('');
      frag.appendChild(span);
      if (c !== null) {
        runStart = i;
        runClass = c;
      }
    }
  }
  return frag;
}
