import { useMemo } from 'react'
import changelogData from '../data/changelog.json'
import type { ChangelogData, ChangelogEntry } from '../types'

const data = changelogData as ChangelogData

type ChangelogSection = {
  title: string
  items: string[]
}

type ParsedBody = {
  sections: ChangelogSection[]
  notes: string[]
}

// 把 commit body 拆成「摘要 / 根本原因 / 影響 / 修法」等區段，
// 過濾掉結尾的 Co-Authored-By 協作資訊。
function parseBody(body: string): ParsedBody {
  const sections: ChangelogSection[] = []
  const notes: string[] = []
  let current: ChangelogSection | null = null

  for (const rawLine of body.split('\n')) {
    const line = rawLine.trim()

    if (!line) {
      continue
    }

    if (/^Co-Authored-By/i.test(line)) {
      continue
    }

    const headerMatch = line.match(/^(.+?)：$/)

    if (headerMatch) {
      current = { title: headerMatch[1], items: [] }
      sections.push(current)
      continue
    }

    const content = line.replace(/^[-*]\s*/, '')

    if (current) {
      current.items.push(content)
    } else {
      notes.push(content)
    }
  }

  return { sections, notes }
}

function ChangelogCard({ entry }: { entry: ChangelogEntry }) {
  const parsed = useMemo(() => parseBody(entry.body), [entry.body])

  return (
    <article className="changelog-card">
      <div className="changelog-card-head">
        <div className="changelog-meta">
          <span className="changelog-date">{entry.date}</span>
          <span className="changelog-hash">{entry.shortHash}</span>
        </div>
        <h3 className="changelog-subject">{entry.subject}</h3>
      </div>

      {parsed.notes.length > 0 ? (
        <div className="changelog-notes">
          {parsed.notes.map((note, index) => (
            <p key={index}>{note}</p>
          ))}
        </div>
      ) : null}

      {parsed.sections.map((section, index) => (
        <div className="changelog-section" key={`${section.title}-${index}`}>
          <p className="changelog-section-title">{section.title}</p>
          <ul className="changelog-section-list">
            {section.items.map((item, itemIndex) => (
              <li key={itemIndex}>{item}</li>
            ))}
          </ul>
        </div>
      ))}
    </article>
  )
}

export function ChangelogPage() {
  const entries = data.entries

  return (
    <section className="page-grid">
      <article className="panel panel-hero">
        <p className="panel-kicker">Changelog</p>
        <h2>更新紀錄</h2>
        <p className="panel-copy">
          這裡列出每次版本更新的內容，目前直接依專案 git commit 產生，由新到舊排列。
        </p>
      </article>

      <article className="panel full-span">
        {entries.length === 0 ? (
          <div className="empty-state">
            <h3>目前沒有更新紀錄</h3>
            <p>尚未產生 changelog 資料，請執行 `npm run gen:changelog` 重新建立。</p>
          </div>
        ) : (
          <div className="changelog-list">
            {entries.map((entry) => (
              <ChangelogCard entry={entry} key={entry.hash} />
            ))}
          </div>
        )}
      </article>
    </section>
  )
}
