import { useState } from 'react'
import type { Style8DSamplePost } from '../lib/styleProfile'
import { parseEvidenceItem, type EvidenceSegment } from '../lib/styleEvidence'

function EvidenceSegments({ segments }: { segments: EvidenceSegment[] }) {
  return (
    <>
      {segments.map((segment, index) => {
        if (segment.type === 'link') {
          return (
            <a
              key={`${segment.href}-${index}`}
              href={segment.href}
              target="_blank"
              rel="noopener noreferrer"
              className="ac-evidence-link"
            >
              {segment.value}
            </a>
          )
        }
        if (segment.type === 'postRef') {
          return (
            <span key={`ref-${segment.postRef}-${index}`} className="ac-evidence-ref">
              {segment.value}
            </span>
          )
        }
        return <span key={`text-${index}`}>{segment.value}</span>
      })}
    </>
  )
}

type Props = {
  evidence: string[]
  samplePosts?: Style8DSamplePost[]
  defaultOpen?: boolean
}

export function EvidenceList({ evidence, samplePosts = [], defaultOpen = false }: Props) {
  const [open, setOpen] = useState(defaultOpen)
  const items = evidence.map((item) => parseEvidenceItem(item, samplePosts))
  const linkCount = items.filter((item) => item.permalink).length

  if (!items.length) return null

  return (
    <div className="ac-persona-8d-evidence">
      <button
        type="button"
        className="ac-evidence-toggle"
        onClick={() => setOpen((prev) => !prev)}
        aria-expanded={open}
      >
        <span className="text-xs font-bold tracking-wide text-ink-secondary">
          分析證據 ({items.length})
        </span>
        <span className="text-[11px] font-semibold text-muted">
          {linkCount > 0 ? `${linkCount} 則可對照原貼` : '展開查看'}
          <span className="ml-1 opacity-70">{open ? '▴' : '▾'}</span>
        </span>
      </button>

      {open ? (
        <ul className="mt-3 space-y-2">
          {items.map((item, index) => (
            <li key={`${item.displayText}-${index}`} className="ac-evidence-card">
              <p className="text-sm leading-relaxed text-ink-secondary">
                <EvidenceSegments segments={item.segments} />
              </p>
              {item.permalink ? (
                <a
                  href={item.permalink}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="ac-evidence-source"
                >
                  查看原貼 {item.postRef ? `#${item.postRef}` : '↗'}
                </a>
              ) : null}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  )
}