import { Text } from "@pikku/mantine/core"
import { asI18n } from "@pikku/react"
import React from "react"

interface EmphasizeProps {
  text: string;
  primary?: boolean
  renderInlineStyles?: boolean
  [key: string]: any
}

function stripInlineTags(text: string) {
  return text
    .replace(/<\/?(strong|i|em)>/g, '')
    .replace(/<br\s*\/?>/g, '\n')
    .replace(/<\/br>/g, '')
}

export function Emphasize({
  text,
  primary = true,
  renderInlineStyles = true,
  ...textProps
}: EmphasizeProps) {
  if (!renderInlineStyles) {
    return <Text {...textProps}>{asI18n(stripInlineTags(text))}</Text>
  }

  // Split text by <strong> and <i> tags while preserving the tags
  const parts = text.split(/(<strong>.*?<\/strong>|<i>.*?<\/i>|<em>.*?<\/em>|<br>.*?<\/br>)/g);

  return (
    <Text {...textProps}>
      {parts.map((part, i) => {
        if ((part.startsWith('<strong>') && part.endsWith('</strong>')) || (part.startsWith('<em>') && part.endsWith('</em>'))){
          // Extract content between <strong> tags
          const content = part.replace(/<\/?strong>/g, '').replace(/<\/?em>/g, '');
          return (
            <Text
              key={i}
              component="strong"
              fw={700}
              span
              c={primary ? 'primary' : undefined}
            >
              {asI18n(content)}
            </Text>
          );
        } else if (part.startsWith('<i>') && part.endsWith('</i>')) {
          // Extract content between <i> tags
          const content = part.replace(/<\/?i>/g, '');
          return (
            <Text key={i} fs="italic" span>
              {asI18n(content)}
            </Text>
          );
        } else if (part.startsWith('<br>') && part.endsWith('</br>')) {
          return (
            <br key={i}/>
          );
        } else {
          // Regular text
          return <React.Fragment key={i}>{asI18n(part)}</React.Fragment>;
        }
      })}
    </Text>
  );
}
