/**
 * Normalize Project `notes` for display when the value is messy HTML (e.g. Quill
 * `ql-editor`) wrapping pasted JSON-ish lines like `"sentence",`.
 */

function decodeBasicHtmlEntities(s: string): string {
  return s
    .replace(/&nbsp;/gi, ' ')
    .replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
    .replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCharCode(parseInt(h, 16)))
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'");
}

/** Block/line breaks to newlines, then strip tags. */
function htmlToPlain(html: string): string {
  const s = html
    .replace(/<\/p>/gi, '\n')
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/div>/gi, '\n')
    .replace(/<\/li>/gi, '\n')
    .replace(/<[^>]+>/g, '');
  return decodeBasicHtmlEntities(s);
}

/**
 * Returns human-readable note text (plain, paragraphs separated by blank lines when needed).
 */
export function formatProjectNotesForDisplay(raw: string | undefined | null): string {
  if (raw == null) return '';
  let s = String(raw).trim();
  if (!s) return '';

  if (s.startsWith('[')) {
    try {
      const parsed = JSON.parse(s) as unknown;
      if (Array.isArray(parsed) && parsed.every(x => typeof x === 'string')) {
        return (parsed as string[])
          .map(x => x.trim())
          .filter(Boolean)
          .join('\n\n');
      }
    } catch {
      /* not a JSON array */
    }
  }

  let html = s;
  const ql = html.match(/<div[^>]*class="[^"]*ql-editor[^"]*"[^>]*>([\s\S]*?)<\/div>/i);
  if (ql) html = ql[1].trim();

  const looksHtml = /<\/?[a-z][\s\S]*>/i.test(html);
  const plain = (looksHtml ? htmlToPlain(html) : html).replace(/\r\n/g, '\n');

  const quotedParts = [...plain.matchAll(/"((?:[^"\\]|\\.)*)"\s*,?/g)].map(m =>
    m[1].replace(/\\"/g, '"'),
  );

  if (quotedParts.length >= 2) {
    return quotedParts.map(p => p.trim()).filter(Boolean).join('\n\n');
  }

  if (quotedParts.length === 1) {
    const withoutQuoted = plain.replace(/"((?:[^"\\]|\\.)*)"\s*,?/g, '').replace(/[\s,]/g, '');
    if (!withoutQuoted) return quotedParts[0].trim();
  }

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