// lib/puck/parseHelpers.ts
// Utilities for parsing simplified textarea inputs used in Puck array fields.

/**
 * Splits a string by newlines into an array. Accepts string or string[].
 * If already an array, returns it as-is.
 */
export function parseLines(input: string | string[] | undefined): string[] {
  if (!input) return [];
  if (Array.isArray(input)) return input.filter(Boolean);
  return input.split('\n').map((s) => s.trim()).filter(Boolean);
}

/**
 * Parses "label: value" lines into { label, value } objects.
 * Accepts string (newline-separated) or array of { label, value }.
 */
export function parseKeyValueLines(
  input: string | { label: string; value: string; highlight?: boolean }[] | undefined
): { label: string; value: string; highlight?: boolean }[] {
  if (!input) return [];
  if (Array.isArray(input)) return input;
  return input
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => {
      const colonIndex = line.indexOf(':');
      if (colonIndex === -1) return { label: line, value: '' };
      return {
        label: line.slice(0, colonIndex).trim(),
        value: line.slice(colonIndex + 1).trim(),
      };
    });
}

/**
 * Parses textarea "key: value" lines into a Record<string, string>.
 * Accepts string or Record<string, string>.
 */
export function parseKeyValueRecord(
  input: string | Record<string, string> | undefined
): Record<string, string> {
  if (!input) return {};
  if (typeof input !== 'string') return input;
  const result: Record<string, string> = {};
  input
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean)
    .forEach((line) => {
      const colonIndex = line.indexOf(':');
      if (colonIndex > 0) {
        result[line.slice(0, colonIndex).trim()] = line.slice(colonIndex + 1).trim();
      }
    });
  return result;
}
