import m from 'mithril'
import {NavHelper} from './helpers/nav.ts'
import htmlPage from './common/htmlPage.ts'

export default async (
  reposConfig: any,
  eleventyConfig: any,
  data: any,
) => {
  const slugify = eleventyConfig.getFilter("slugify")
  const nav = NavHelper(reposConfig, slugify, data.flatRel.repoName, data.flatRel.relName)

  const branchesWithWorkInProgress = data.flatRels.filter(rel => rel.type === "branch" && rel.ahead > 0)
  const branchesFullyMerged = data.flatRels.filter(rel => rel.type === "branch" && rel.ahead === 0)

  const branchCards = (branches) => {
    return m('ul', branches.map((branch) => {
      return branch.repoName === data.flatRel.repoName ?
        m('li', [
          m('a', {
            href: `${data.reposPath}/${slugify(branch.repoName)}/branch/${slugify(branch.relName)}/branches`
          }, branch.relName),
          branch.relName === data.flatRel.relName
            ? m('div', {class: "badge rounded-pill bg-secondary mx-1"}, 'current') : null,
          branch.relName === data.reposConfig.repos[branch.repoName].defaultBranch
            ? m('div', {class: "badge rounded-pill bg-info text-dark mx-1"}, 'default') : null,
          m('ul', [
            m('li', [
              `${branch.ahead} commits ahead, ${branch.behind} commits behind `,
              m('span', {class: 'font-monospace'}, branch.compareTo)
            ]),
            branch.description ? m('li', branch.description) : null
          ]),
        ])
      : null
    }))
  }

  const pageContent = [
    m('h1', {class: 'fs-2'}, 'Branches with unmerged commits'),
    branchCards(branchesWithWorkInProgress),
    m('h1', {class: 'fs-2'}, 'Branches that are fully merged'),
    branchCards(branchesFullyMerged),
  ]

  return await htmlPage(reposConfig, eleventyConfig, data, pageContent)
}
