import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

interface ChangelogEntry {
  version: string;
  sections: { heading: string; items: string[] }[];
}

function parseChangelog(markdown: string): ChangelogEntry[] {
  const entries: ChangelogEntry[] = [];
  let current: ChangelogEntry | null = null;
  let currentSection: { heading: string; items: string[] } | null = null;

  for (const line of markdown.split("\n")) {
    const trimmed = line.trim();

    const versionMatch = trimmed.match(/^## \[?([^\]]+)\]?/);
    if (versionMatch) {
      if (currentSection && current) current.sections.push(currentSection);
      if (current) entries.push(current);
      current = { version: versionMatch[1], sections: [] };
      currentSection = null;
      continue;
    }

    const sectionMatch = trimmed.match(/^### (.+)/);
    if (sectionMatch && current) {
      if (currentSection) current.sections.push(currentSection);
      currentSection = { heading: sectionMatch[1], items: [] };
      continue;
    }

    if (trimmed.startsWith("- ") && currentSection) {
      currentSection.items.push(trimmed.slice(2));
    }
  }

  if (currentSection && current) current.sections.push(currentSection);
  if (current) entries.push(current);

  return entries;
}

export default function ChangelogContent() {
  const { t, i18n } = useTranslation();
  const [entries, setEntries] = useState<ChangelogEntry[]>([]);

  useEffect(() => {
    const file = i18n.language === "fr" ? "/CHANGELOG.fr.md" : "/CHANGELOG.md";
    fetch(file)
      .then((r) => r.text())
      .then((text) => setEntries(parseChangelog(text)))
      .catch(() => setEntries([]));
  }, [i18n.language]);

  if (entries.length === 0) {
    return (
      <p className="text-[var(--muted-foreground)]">{t("changelog.empty")}</p>
    );
  }

  return (
    <div className="space-y-6">
      {entries.map((entry) => (
        <div
          key={entry.version}
          className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 space-y-3"
        >
          <h3 className="text-lg font-semibold">{entry.version}</h3>
          {entry.sections.map((section, si) => (
            <div key={si} className="space-y-1.5">
              <h4 className="text-sm font-semibold text-[var(--primary)]">
                {section.heading}
              </h4>
              <ul className="space-y-1">
                {section.items.map((item, ii) => (
                  <li
                    key={ii}
                    className="text-sm text-[var(--muted-foreground)] pl-3"
                  >
                    {"• "}
                    {item.replace(/\*\*(.+?)\*\*/g, "$1")}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}
