import { RichText } from '@atproto/api'

interface BioTextProps {
  text: string
  className?: string
}

export default function BioText({ text, className }: BioTextProps) {
  const rt = new RichText({ text })
  rt.detectFacetsWithoutResolution()

  const segments = [...rt.segments()]

  return (
    <p className={className}>
      {segments.map((seg, i) => {
        if (seg.isLink()) {
          return (
            <a
              key={i}
              href={seg.link!.uri}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-600 dark:text-blue-400 hover:underline"
            >
              {seg.text}
            </a>
          )
        }
        if (seg.isMention()) {
          // handle text is "@foo.bsky.social"; strip leading @ for the URL
          const handle = seg.text.startsWith('@') ? seg.text.slice(1) : seg.text
          return (
            <a
              key={i}
              href={`/${handle}`}
              className="text-blue-600 dark:text-blue-400 hover:underline"
            >
              {seg.text}
            </a>
          )
        }
        if (seg.isTag()) {
          return (
            <a
              key={i}
              href={`https://bsky.app/hashtag/${encodeURIComponent(seg.tag!.tag)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-600 dark:text-blue-400 hover:underline"
            >
              {seg.text}
            </a>
          )
        }
        return seg.text
      })}
    </p>
  )
}
