import type { Metadata } from "next";
import { CircleDot } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { buildMetadata } from "@/lib/seo";

export const metadata: Metadata = buildMetadata({
  title: "Changelog",
  description: "Release notes for Markdown Viewer — new features, improvements, and bug fixes.",
  path: "/changelog",
});

type Release = {
  version: string;
  date: string;
  highlight?: string;
  added?: string[];
  changed?: string[];
  fixed?: string[];
};

const RELEASES: Release[] = [
  {
    version: "1.5.0",
    date: "2025-11-25",
    highlight: "Math, diagrams, and a real PDF export.",
    added: [
      "Math support via KaTeX — inline `$…$` and block `$$…$$`, lazy-loaded",
      "Mermaid diagrams in fenced ```mermaid blocks (lazy, theme-aware)",
      "Emoji shortcodes (~250) — `:smile:`, `:rocket:`, `:100:`, …",
      "PDF download uses the same HTML as Print, then saves a .pdf file (no print dialog)",
      "Find & replace with regex support — `Ctrl/⌘ + F`",
      "Focus / Zen mode hides all chrome — `Ctrl/⌘ + .`",
      "Auto-generated table of contents from document headings",
      "Smart paste — rich HTML on the clipboard auto-converts to Markdown",
      "Readability stats — sentences, avg sentence length, top words, Flesch score",
      "Load Sample action + showcase template",
      "New tool: HTML to Markdown converter (live)",
      "New tool: Markdown to PDF (dedicated landing)",
      "New tool: Markdown Table Generator (visual builder)",
      "Tools index at /tools",
      "Blog: tag pages and related-posts on every article",
    ],
    changed: [
      "Default document now showcases every editor feature",
      "Confirm dialog modals replace native `confirm()` / `prompt()`",
      "Editor footer hidden — no extra page scrollbar on /editor",
      "Find & replace popup pinned to top-right of the editor",
    ],
  },
  {
    version: "1.4.0",
    date: "2025-11-12",
    added: [
      "Shareable preview links via the toolbar Share button",
      "Drag-and-drop import for `.md` files",
      "New 'Insert template' palette (Ctrl/⌘ + Shift + T)",
    ],
    changed: [
      "Outline panel now shows H1–H6 with indentation",
      "Improved sanitization for raw HTML in preview",
    ],
  },
  {
    version: "1.3.0",
    date: "2025-10-04",
    added: [
      "Multiple drafts with rename, close, and autosave",
      "Markdown linter with auto-fix",
      "Table and checklist generators",
    ],
    fixed: ["Scroll sync drift on long documents", "Dark mode flash on first load"],
  },
  {
    version: "1.2.0",
    date: "2025-08-15",
    added: [
      "GitHub Flavored Markdown extensions (tables, task lists, strikethrough)",
      "Syntax highlighting for 150+ languages",
      "PDF export via the browser's print dialog",
    ],
  },
  {
    version: "1.1.0",
    date: "2025-07-02",
    added: ["Live split-screen preview", "Word count, reading time, and outline navigator"],
  },
  {
    version: "1.0.0",
    date: "2025-06-10",
    added: ["Initial public release of Markdown Viewer"],
  },
];

function groupByYear(releases: Release[]): Map<string, Release[]> {
  const groups = new Map<string, Release[]>();
  for (const release of releases) {
    const year = new Date(release.date).getFullYear().toString();
    const existing = groups.get(year);
    if (existing) {
      existing.push(release);
    } else {
      groups.set(year, [release]);
    }
  }
  return groups;
}

export default function ChangelogPage() {
  const groups = groupByYear(RELEASES);

  return (
    <div className="container max-w-3xl py-12 sm:py-16">
      <header className="mb-10">
        <p className="text-sm font-medium uppercase tracking-wider text-primary">Changelog</p>
        <h1 className="mt-2 text-3xl font-semibold tracking-tight sm:text-4xl">Release notes</h1>
        <p className="mt-3 text-muted-foreground">
          Every release of Markdown Viewer, newest first. We follow{" "}
          <a
            href="https://keepachangelog.com"
            className="underline-offset-4 hover:underline"
            target="_blank"
            rel="noopener noreferrer"
          >
            Keep a Changelog
          </a>{" "}
          and semantic versioning.
        </p>
      </header>

      <div className="space-y-12">
        {Array.from(groups.entries()).map(([year, releases]) => (
          <section key={year} aria-labelledby={`year-${year}`}>
            <div className="mb-6 flex items-baseline gap-3">
              <h2
                id={`year-${year}`}
                className="text-2xl font-semibold tabular-nums tracking-tight text-muted-foreground"
              >
                {year}
              </h2>
              <span className="text-xs text-muted-foreground">
                {releases.length} {releases.length === 1 ? "release" : "releases"}
              </span>
            </div>

            <ol className="relative space-y-10 border-l-2 border-border/70 pl-6 sm:pl-8">
              {releases.map((release, idx) => (
                <li key={release.version} className="relative">
                  <span
                    aria-hidden
                    className="absolute -left-[33px] top-2 grid h-6 w-6 place-items-center rounded-full border-2 border-background bg-primary sm:-left-[41px]"
                  >
                    <CircleDot className="h-3 w-3 text-primary-foreground" />
                  </span>

                  <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
                    <h3 className="text-xl font-semibold">
                      v{release.version}
                    </h3>
                    <time
                      className="text-sm text-muted-foreground"
                      dateTime={release.date}
                    >
                      {new Date(release.date).toLocaleDateString("en-US", {
                        dateStyle: "long",
                      })}
                    </time>
                    {idx === 0 && releases === groups.get(year) ? (
                      <Badge variant="success" className="text-[10px]">
                        Latest
                      </Badge>
                    ) : null}
                  </div>

                  {release.highlight ? (
                    <p className="mt-2 text-sm text-foreground">{release.highlight}</p>
                  ) : null}

                  <div className="mt-4 rounded-xl border bg-card p-5">
                    {release.added ? (
                      <Section title="Added" items={release.added} variant="added" />
                    ) : null}
                    {release.changed ? (
                      <Section title="Changed" items={release.changed} variant="changed" />
                    ) : null}
                    {release.fixed ? (
                      <Section title="Fixed" items={release.fixed} variant="fixed" />
                    ) : null}
                  </div>
                </li>
              ))}
            </ol>
          </section>
        ))}
      </div>
    </div>
  );
}

function Section({
  title,
  items,
  variant,
}: {
  title: string;
  items: string[];
  variant: "added" | "changed" | "fixed";
}) {
  const colors = {
    added: "text-emerald-600 dark:text-emerald-400",
    changed: "text-amber-600 dark:text-amber-400",
    fixed: "text-blue-600 dark:text-blue-400",
  } as const;
  return (
    <div className="mt-3 first:mt-0">
      <h4 className={`text-xs font-semibold uppercase tracking-wider ${colors[variant]}`}>
        {title}
      </h4>
      <ul className="mt-1.5 list-disc space-y-1 pl-5 text-sm text-muted-foreground marker:text-muted-foreground/60">
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}
