import React, { useMemo } from 'react';
import type { ResearchNote } from '../../../types/research';

const sanitizeNoteHtml = (html: string) => {
  if (typeof document === 'undefined') {
    return html;
  }

  const template = document.createElement('template');
  template.innerHTML = html;
  template.content.querySelectorAll('script, style, iframe, object, embed').forEach((node) => {
    node.remove();
  });
  template.content.querySelectorAll('*').forEach((node) => {
    Array.from(node.attributes).forEach((attribute) => {
      if (attribute.name.startsWith('on')) {
        node.removeAttribute(attribute.name);
      }
    });
  });
  return template.innerHTML;
};

export const ResearchNoteBody: React.FC<{ note: ResearchNote }> = ({ note }) => {
  const sanitizedHtml = useMemo(
    () => (note.bodyHtml ? sanitizeNoteHtml(note.bodyHtml) : ''),
    [note.bodyHtml],
  );

  if (!note.bodyHtml) {
    return <p className="whitespace-pre-wrap text-sm leading-7 text-term-text">{note.rawText}</p>;
  }

  return (
    <div
      className="research-note-body text-sm leading-7 text-term-text"
      dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
    />
  );
};
