export type CopyMode = 'plain' | 'markdown';

const splitTableRow = (line: string) =>
  line
    .trim()
    .replace(/^\|/, '')
    .replace(/\|$/, '')
    .split('|')
    .map((c) => c.trim());

const isTableDividerLine = (line: string) =>
  /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(line);

export function markdownToPlainText(input: string) {
  let text = String(input ?? '').replace(/\r\n/g, '\n');

  const lines = text.split('\n');
  const out: string[] = [];

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const next = lines[i + 1];

    if (line.includes('|') && next && isTableDividerLine(next)) {
      const header = splitTableRow(line);
      out.push(header.join('\t'));
      i += 1;
      for (let j = i + 1; j < lines.length; j++) {
        const rowLine = lines[j];
        if (!rowLine.trim()) {
          i = j;
          break;
        }
        if (!rowLine.includes('|')) {
          i = j - 1;
          break;
        }
        out.push(splitTableRow(rowLine).join('\t'));
        i = j;
      }
      continue;
    }

    out.push(line);
  }

  text = out.join('\n');

  text = text.replace(/```[^\n]*\n([\s\S]*?)```/g, (_, code) => String(code).replace(/\n$/, ''));
  text = text.replace(/`([^`]+)`/g, '$1');
  text = text.replace(/^#{1,6}\s+/gm, '');
  text = text.replace(/^>\s?/gm, '');
  text = text.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, url) => (alt ? `${alt} (${url})` : String(url)));
  text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)');
  text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
  text = text.replace(/__([^_]+)__/g, '$1');
  text = text.replace(/\*([^*]+)\*/g, '$1');
  text = text.replace(/_([^_]+)_/g, '$1');

  text = text.replace(/\n{3,}/g, '\n\n').trim();
  return text;
}

