---
import { getCollection, render } from "astro:content";
import CopyReleaseNotes from "./CopyReleaseNotes.astro";
import { getLatestRelease } from "@lib/github";

interface Props {
  showUnreleased?: boolean;
}

const { showUnreleased = false } = Astro.props;

const releaseData = await getLatestRelease("gruntwork-io", "terragrunt");
const latestVersion = (releaseData?.tag_name ?? "v0.0.0").replace(/^v/, "");

function isReleased(version: string): boolean {
  if (!version.startsWith("v")) return false;

  const v = version.replace(/^v/, "");
  return v.localeCompare(latestVersion, undefined, { numeric: true }) <= 0;
}

const allEntries = await getCollection("changelog");

// Sort by version descending, with non-semver entries (e.g. "Unreleased") always first
allEntries.sort((a, b) => {
  const aIsVersion = a.data.version.startsWith("v");
  const bIsVersion = b.data.version.startsWith("v");
  if (!aIsVersion && bIsVersion) return -1;
  if (aIsVersion && !bIsVersion) return 1;
  return b.data.version.localeCompare(a.data.version, undefined, { numeric: true });
});

const entries = showUnreleased
  ? allEntries
  : allEntries.filter((entry) => isReleased(entry.data.version));

const siteUrl = Astro.site?.origin ?? "https://docs.terragrunt.com";

function prepareForGitHub(body: string): string {
  let result = body;

  // Make relative links absolute
  result = result.replace(/\]\(\//g, `](${siteUrl}/`);

  // Bump heading levels: #### -> ###, ### -> ##
  // Process #### first to avoid double-replacement
  result = result.replace(/^####\s/gm, "### ");
  result = result.replace(/^###\s/gm, "## ");

  // Remove --- separators (standalone lines)
  result = result.replace(/^\s*---\s*$/gm, "");

  // Clean up excessive blank lines left by separator removal
  result = result.replace(/\n{3,}/g, "\n\n");

  return result.trim();
}

const rendered = await Promise.all(
  entries.map(async (entry) => {
    const { Content } = await render(entry);
    const githubMarkdown = prepareForGitHub(entry.body ?? "");
    return { entry, Content, githubMarkdown };
  })
);
---

{rendered.map(({ entry, Content, githubMarkdown }) => (
  <div>
    <h2 id={entry.data.version}>{entry.data.version}<a class="anchor-link" href={`#${entry.data.version}`}><span aria-hidden="true" class="anchor-icon"></span></a></h2>
    <hr />
    <Content />
    {entry.data.version.startsWith("v") && (
      <aside class="copy-section">
        <p class="copy-heading">Copy to GitHub Releases</p>
        <p class="copy-description">Copy these release notes with absolute URLs and heading levels adjusted for use in a <a href={`https://github.com/gruntwork-io/terragrunt/releases/new?tag=${entry.data.version}`}>GitHub Release</a>.</p>
        <CopyReleaseNotes markdown={githubMarkdown} />
      </aside>
    )}
  </div>
))}

<style>
  .copy-section {
    margin-top: 2rem;
    padding: 1.25rem;
    border: 1px solid var(--sl-color-docs-stroke);
    border-radius: 0.5rem;
    background: var(--sl-color-bg-nav);
  }

  .copy-heading {
    font-size: 0.875rem;
    font-weight: 600;
    font-family: var(--font-sans);
    color: var(--sl-color-white);
    margin: 0 0 0.375rem;
  }

  .copy-description {
    font-size: 0.8125rem;
    color: var(--sl-color-gray-3);
    margin: 0 0 0.75rem;
    line-height: 1.5;
  }

  .copy-description a {
    color: var(--sl-color-accent);
  }
</style>
