import type { ResearchMapData } from '../types/brand'
import { Badge, Card } from './ui'

type ResearchMapPanelProps = {
  map: ResearchMapData | null | undefined
  loading?: boolean
  variant?: 'placement' | 'copy'
}

function ListBlock({ title, items, tone }: { title: string; items: string[]; tone?: 'danger' }) {
  if (!items.length) return null
  return (
    <Card className={`space-y-2 p-4 ${tone === 'danger' ? 'border-danger/30 bg-danger-soft/30' : ''}`}>
      <div className="flex items-center gap-2">
        <p className="text-xs font-bold tracking-wide text-muted uppercase">{title}</p>
        <Badge tone={tone === 'danger' ? 'warning' : 'neutral'}>{items.length}</Badge>
      </div>
      <ul className="space-y-1.5 text-sm leading-relaxed text-ink">
        {items.map((item) => (
          <li key={item} className="flex gap-2">
            <span className="text-muted">·</span>
            <span>{item}</span>
          </li>
        ))}
      </ul>
    </Card>
  )
}

export function ResearchMapPanel({ map, loading, variant = 'placement' }: ResearchMapPanelProps) {
  const copyMap = map as ResearchMapData & { suggested_tags?: string[]; benchmark_notes?: string }
  if (loading) {
    return <p className="text-sm text-muted">研究地圖產生中…</p>
  }
  if (!map || (!map.audience_summary && !map.questions?.length)) {
    return (
      <p className="text-sm text-ink-secondary">
        {variant === 'copy'
          ? '按「產生研究地圖」後會出現爆款方向、建議搜尋 tag 與不要模仿的內容。'
          : '建立主題後會自動產生置入研究地圖（受眾、內容目標、受眾會問什麼、內容支柱、不要碰）。'}
      </p>
    )
  }

  return (
    <div className="grid gap-4">
      {map.audience_summary ? (
        <Card className="space-y-2 border-brand/20 bg-brand-soft/20 p-4">
          <p className="text-xs font-bold tracking-wide text-brand uppercase">受眾是誰</p>
          <p className="text-sm leading-relaxed text-ink">{map.audience_summary}</p>
        </Card>
      ) : null}
      {map.content_goal ? (
        <Card className="space-y-2 p-4">
          <p className="text-xs font-bold tracking-wide text-muted uppercase">內容目標</p>
          <p className="text-sm leading-relaxed text-ink">{map.content_goal}</p>
        </Card>
      ) : null}
      <ListBlock title="受眾會問什麼" items={map.questions ?? []} />
      <ListBlock title="內容支柱" items={map.pillars ?? []} />
      <ListBlock
        title={variant === 'copy' ? '不要模仿' : '不要碰'}
        items={map.exclusions ?? []}
        tone="danger"
      />
      {variant === 'copy' && copyMap.suggested_tags?.length ? (
        <ListBlock title="爆款搜尋 tag" items={copyMap.suggested_tags} />
      ) : null}
      {variant === 'copy' && copyMap.benchmark_notes ? (
        <Card className="space-y-2 p-4">
          <p className="text-xs font-bold tracking-wide text-muted uppercase">爆款標準</p>
          <p className="text-sm leading-relaxed text-ink">{copyMap.benchmark_notes}</p>
        </Card>
      ) : null}
    </div>
  )
}