import { Download } from "lucide-react";
import fs from "fs";
import path from "path";

export default function AGB() {
  const filePath = path.join(process.cwd(), "context/agbs.md");
  const fileContent = fs.readFileSync(filePath, "utf8");

  // Split by double newlines to get major blocks (headers + their first paragraphs, or subsequent paragraphs)
  const blocks = fileContent
    .split(/\n\s*\n/)
    .map((b) => b.trim())
    .filter((b) => b !== "");

  const title = blocks[0] || "Liefer- und Zahlungsbedingungen";
  const stand = blocks[1] || "Stand Januar 2026";

  const sections: { title: string; content: string[] }[] = [];
  let currentSection: { title: string; content: string[] } | null = null;

  // Skip title and stand
  blocks.slice(2).forEach((block) => {
    const lines = block
      .split("\n")
      .map((l) => l.trim())
      .filter((l) => l !== "");
    if (lines.length === 0) return;

    const firstLine = lines[0];

    if (/^\d+\./.test(firstLine)) {
      // New section
      if (currentSection) sections.push(currentSection);

      currentSection = { title: firstLine, content: [] };

      // If there are more lines in this block, they form the first paragraph(s)
      if (lines.length > 1) {
        // Join subsequent lines as they might be part of the same paragraph
        // In this MD, we'll assume lines in the same block belong together
        // unless they are clearly separate paragraphs (but we already split by double newline)
        const remainingText = lines.slice(1).join(" ");
        if (remainingText) currentSection.content.push(remainingText);
      }
    } else if (currentSection) {
      // Continuation of current section
      const blockText = lines.join(" ");
      if (blockText) currentSection.content.push(blockText);
    }
  });
  if (currentSection) sections.push(currentSection);

  // The last block is the footer
  const footer = blocks[blocks.length - 1];
  if (sections.length > 0) {
    const lastSection = sections[sections.length - 1];
    if (lastSection.content.includes(footer) || lastSection.title === footer) {
      lastSection.content = lastSection.content.filter((c) => c !== footer);
      if (sections[sections.length - 1].title === footer) {
        sections.pop();
      }
    }
  }

  return (
    <div className="bg-slate-50 min-h-screen pt-40 pb-20">
      <div className="container-custom">
        <div className="max-w-4xl mx-auto bg-white p-8 md:p-12 rounded-[2.5rem] shadow-sm border border-slate-100">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
            <div>
              <h1 className="text-4xl font-extrabold text-primary mb-2">
                {title}
              </h1>
              <p className="text-slate-500 font-medium">{stand}</p>
            </div>
            <a
              href="/assets/AGB MB Grid 3-2026.pdf"
              download
              className="btn-primary !py-3 !px-6 flex items-center gap-2"
            >
              <Download size={18} />
              Als PDF herunterladen
            </a>
          </div>

          <div className="space-y-8 text-slate-600 leading-relaxed">
            {sections.map((section, index) => (
              <div key={index}>
                <h2 className="text-2xl font-bold text-primary mb-4">
                  {section.title}
                </h2>
                <div className="space-y-4">
                  {section.content.map((paragraph, pIndex) => (
                    <p key={pIndex}>
                      {paragraph.split(/(\[.*?\]\(.*?\))/g).map((part, i) => {
                        const match = part.match(/\[(.*?)\]\((.*?)\)/);
                        if (match) {
                          return (
                            <a
                              key={i}
                              href={match[2]}
                              className="text-primary hover:underline font-medium"
                              download={match[2].endsWith(".pdf")}
                            >
                              {match[1]}
                            </a>
                          );
                        }
                        return part;
                      })}
                    </p>
                  ))}
                </div>
              </div>
            ))}

            <div className="pt-8 border-t border-slate-100">
              <p className="font-bold text-primary">{footer}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
