"use client"

import React from "react"

interface HighlightTextProps {
  text: string
  query: string
  className?: string
  highlightClassName?: string
}

/**
 * Component that highlights matching text within content
 * Splits text by the query and wraps matches in a highlight span
 */
export function HighlightText({
  text,
  query,
  className = "",
  highlightClassName = "bg-yellow-500/30 text-yellow-200 font-medium",
}: HighlightTextProps) {
  if (!query.trim() || !text) {
    return <span className={className}>{text}</span>
  }

  const normalizedQuery = query.toLowerCase()
  const normalizedText = text.toLowerCase()
  
  // Split text by query matches
  const parts: { text: string; match: boolean }[] = []
  let lastIndex = 0
  let index = normalizedText.indexOf(normalizedQuery)

  while (index !== -1) {
    // Add text before match
    if (index > lastIndex) {
      parts.push({
        text: text.slice(lastIndex, index),
        match: false,
      })
    }
    
    // Add the match
    parts.push({
      text: text.slice(index, index + query.length),
      match: true,
    })
    
    lastIndex = index + query.length
    index = normalizedText.indexOf(normalizedQuery, lastIndex)
  }

  // Add remaining text
  if (lastIndex < text.length) {
    parts.push({
      text: text.slice(lastIndex),
      match: false,
    })
  }

  return (
    <span className={className}>
      {parts.map((part, i) =>
        part.match ? (
          <mark
            key={i}
            className={`${highlightClassName} rounded px-0.5 -mx-0.5`}
          >
            {part.text}
          </mark>
        ) : (
          <span key={i}>{part.text}</span>
        )
      )}
    </span>
  )
}

/**
 * Highlight multiple fields, returning null if no matches found
 * Useful for conditionally highlighting description, tags, etc.
 */
interface HighlightMatch {
  field: string
  value: string
}

interface HighlightMatchesProps {
  matches: HighlightMatch[]
  query: string
  className?: string
  highlightClassName?: string
  maxLength?: number
}

export function HighlightMatches({
  matches,
  query,
  className = "text-sm text-slate-400",
  highlightClassName = "bg-yellow-500/30 text-yellow-200 font-medium",
  maxLength = 120,
}: HighlightMatchesProps) {
  if (!query.trim()) return null

  const normalizedQuery = query.toLowerCase()
  
  // Find which matches contain the query
  const matchingFields = matches.filter((match) =>
    match.value.toLowerCase().includes(normalizedQuery)
  )

  if (matchingFields.length === 0) return null

  return (
    <div className={className}>
      {matchingFields.map((match, index) => (
        <div key={match.field} className="flex items-start gap-2">
          <span className="text-slate-500 shrink-0">{match.field}:</span>
          <HighlightText
            text={
              match.value.length > maxLength
                ? match.value.slice(0, maxLength) + "..."
                : match.value
            }
            query={query}
            highlightClassName={highlightClassName}
          />
        </div>
      ))}
    </div>
  )
}

export default HighlightText
