"use client";

import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import {
  FileSpreadsheet,
  FileDown,
  Download,
  CheckCircle2,
  AlertTriangle,
  Landmark,
  UserCheck,
  FolderKanban,
  Lock,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { useDashboardShell } from "@/components/dashboard/DashboardShellContext";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { fetchProjects, fetchServerReceipts, getCurrentUserId, ServerProject } from "@/lib/storage/server";
import { receiptNeedsAttention } from "@/lib/ai/recalculate";
import { apiFetch } from "@/lib/csrf/client";

type ExportKind = "xlsx" | "csv" | "pdf";

const EXPORT_LABELS: Record<ExportKind, { de: string; en: string }> = {
  xlsx: { de: "Excel (.xlsx)", en: "Excel (.xlsx)" },
  csv: { de: "CSV", en: "CSV" },
  pdf: { de: "PDF-Report", en: "PDF report" },
};

/** Lädt einen Blob als Datei herunter. */
function downloadBlob(blob: Blob, fileName: string) {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
}

/** Liest den Dateinamen aus `Content-Disposition`, sonst `fallback`. */
function fileNameFrom(response: Response, fallback: string): string {
  const header = response.headers.get("content-disposition") ?? "";
  const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(header);
  if (!match) return fallback;
  try {
    return decodeURIComponent(match[1]);
  } catch {
    return match[1];
  }
}

export default function ExportControlPage() {
  const { language } = useI18n();
  const isDe = language === "de";
  const { openPaywall } = useDashboardShell();

  const [receipts, setReceipts] = useState<ProcessedReceipt[]>([]);
  const [projects, setProjects] = useState<ServerProject[]>([]);
  const [isPro, setIsPro] = useState(false);
  const [selectedProjectId, setSelectedProjectId] = useState<string>("");

  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [targetScope, setTargetScope] = useState<"ALL" | "VALIDATED">("ALL");
  const [isExporting, setIsExporting] = useState(false);
  const [pendingExport, setPendingExport] = useState<ExportKind | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [warnings, setWarnings] = useState<string[]>([]);

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const res = await apiFetch("/api/auth/session");
        const data = res.ok ? await res.json() : null;
        if (!cancelled && data?.user) {
          setIsPro(Boolean(data.user.isPro));
        }
      } catch {}

      const uid = await getCurrentUserId();
      const [stored, projectRows] = await Promise.all([
        fetchServerReceipts(uid),
        fetchProjects(),
      ]);
      if (cancelled) return;
      setReceipts(stored);
      setProjects(projectRows);

      if (typeof window !== "undefined") {
        const params = new URLSearchParams(window.location.search);
        const urlProjectId = params.get("projectId");
        if (urlProjectId) {
          setSelectedProjectId(urlProjectId);
        }
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, []);

  /**
   * Belege im gewählten Zeitraum, Projekt und Prüf-Umfang.
   */
  const filteredReceipts = useMemo(() => {
    return receipts.filter((r) => {
      const iso = r.date?.isoDate;
      if (startDate && (!iso || iso < startDate)) return false;
      if (endDate && (!iso || iso > endDate)) return false;
      if (targetScope === "VALIDATED" && receiptNeedsAttention(r)) return false;
      if (selectedProjectId === "unassigned" && r.projectId) return false;
      if (
        selectedProjectId &&
        selectedProjectId !== "unassigned" &&
        r.projectId !== selectedProjectId
      ) {
        return false;
      }
      return true;
    });
  }, [receipts, startDate, endDate, targetScope, selectedProjectId]);

  const unreviewed = useMemo(
    () => filteredReceipts.filter((r) => receiptNeedsAttention(r)),
    [filteredReceipts]
  );

  const estimatedBytes = filteredReceipts.length * 1400 + 4000;
  const estimatedKb = (estimatedBytes / 1024).toFixed(1);

  /* ---------------------------------------------------------------- */
  /* Export                                                            */
  /* ---------------------------------------------------------------- */

  const runExport = async (kind: ExportKind) => {
    setPendingExport(null);
    setErrorMessage(null);
    setWarnings([]);

    if (filteredReceipts.length === 0) {
      setErrorMessage(isDe ? "Keine Belege im aktuellen Filter – nichts zu exportieren." : "No receipts in current filter – nothing to export.");
      return;
    }

    const today = new Date().toISOString().split("T")[0];
    const endpoint =
      kind === "xlsx" ? "/api/export/excel" : kind === "pdf" ? "/api/export/pdf" : "/api/export/csv";
    const fallbackName =
      kind === "xlsx"
        ? (isDe ? `Belege_Export_${today}.xlsx` : `Receipts_Export_${today}.xlsx`)
        : kind === "pdf"
        ? (isDe ? `Belege_Export_${today}.pdf` : `Receipts_Export_${today}.pdf`)
        : (isDe ? `Belege_Export_${today}.csv` : `Receipts_Export_${today}.csv`);

    const body: Record<string, unknown> = { receipts: filteredReceipts };
    if (kind === "pdf") {
      body.locale = language;
      if (startDate) body.dateFrom = startDate;
      if (endDate) body.dateTo = endDate;
    }

    setIsExporting(true);
    try {
      const res = await apiFetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      const contentType = res.headers.get("content-type") ?? "";

      // Fehler und Hinweise kommen als JSON, die fertige Datei als Blob.
      if (contentType.includes("application/json")) {
        const payload = (await res.json()) as {
          error?: string;
          warnings?: string[];
          skipped?: Array<{ receiptId: string; reason: string }>;
        };
        if (res.status === 401 || res.status === 403 || payload.error === "pro_required" || payload.error === "unauthorized") {
          openPaywall();
          return;
        }
        if (!res.ok || payload.error) {
          setErrorMessage(payload.error || (isDe ? `Export fehlgeschlagen (${res.status}).` : `Export failed (${res.status}).`));
          return;
        }
        setWarnings([
          ...(payload.warnings ?? []),
          ...(payload.skipped ?? []).map((entry) => entry.reason),
        ]);
        return;
      }

      if (!res.ok) {
        setErrorMessage(
          `${isDe ? EXPORT_LABELS[kind].de : EXPORT_LABELS[kind].en}: ${isDe ? `Export fehlgeschlagen (Status ${res.status}).` : `Export failed (Status ${res.status}).`}`
        );
        return;
      }

      const warningHeader = res.headers.get("x-export-warnings");
      if (warningHeader) {
        try {
          const parsed = JSON.parse(warningHeader);
          if (Array.isArray(parsed)) setWarnings(parsed.map(String));
        } catch {
          setWarnings([warningHeader]);
        }
      }

      downloadBlob(await res.blob(), fileNameFrom(res, fallbackName));
    } catch (err) {
      console.error(err);
      setErrorMessage(
        `${isDe ? EXPORT_LABELS[kind].de : EXPORT_LABELS[kind].en}: ${isDe ? "Export fehlgeschlagen. Bitte erneut versuchen." : "Export failed. Please try again."}`
      );
    } finally {
      setIsExporting(false);
    }
  };

  /**
   * Startet einen Export – fragt aber vorher nach, wenn ungeprüfte Belege
   * dabei sind. Genau diese Belege sind es, die später als Produktfehler
   * zurückkommen.
   */
  const requestExport = (kind: ExportKind) => {
    setErrorMessage(null);
    setWarnings([]);
    if (!isPro) {
      openPaywall();
      return;
    }
    if (unreviewed.length > 0) {
      setPendingExport(kind);
      return;
    }
    void runExport(kind);
  };

  return (
    <div className="space-y-8 font-sans">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-6 border-b border-[#E2E8F0]">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="w-2.5 h-2.5 bg-black"></span>
            <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
              {isDe ? "EXPORT" : "EXPORT"}
            </span>
          </div>
          <h1 className="font-display text-3xl sm:text-4xl font-bold tracking-tight text-black">
            {isDe ? "Belege exportieren" : "Export receipts"}
          </h1>
          <p className="text-xs text-[#64748B] font-mono mt-1">
            {isDe
              ? "Belege als Excel, CSV oder PDF exportieren."
              : "Export receipt datasets as Excel, CSV, or PDF."}
          </p>
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={() => requestExport("xlsx")}
            disabled={isExporting || filteredReceipts.length === 0}
            className="px-5 py-2.5 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors font-medium flex items-center gap-2 disabled:opacity-40"
            title={isDe ? "Alle gefilterten Belege als Excel-Datei herunterladen" : "Download all filtered receipts as Excel file"}
          >
            <Download className="w-4 h-4" />
            <span>{isDe ? "Export starten" : "Start export"}</span>
          </button>
        </div>
      </div>

      {/* Warnung: ungeprüfte Belege */}
      {unreviewed.length > 0 && (
        <div
          data-testid="unreviewed-warning"
          className="border border-[#F59E0B] bg-[#FEF3C7] p-4"
        >
          <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
            <div className="flex items-start gap-3">
              <div className="flex h-8 w-8 shrink-0 items-center justify-center bg-black text-white">
                <AlertTriangle className="h-4 w-4 text-[#F59E0B]" />
              </div>
              <div>
                <p className="text-sm font-bold text-black">
                  {isDe
                    ? `${unreviewed.length} von ${filteredReceipts.length} Belegen sind ungeprüft.`
                    : `${unreviewed.length} of ${filteredReceipts.length} receipts are unreviewed.`}
                </p>
                <p className="mt-0.5 text-xs text-[#78350F]">
                  {isDe
                    ? "Ungeprüfte Belege gehen mit den Zahlen der Erkennung in den Export – Fehler landen so direkt im Export."
                    : "Unreviewed receipts will be exported with raw AI extraction values – undetected errors may land directly in your export."}
                </p>
                <ul className="mt-2 space-y-0.5 font-mono text-[10px] text-[#78350F]">
                  {unreviewed.slice(0, 3).map((r) => (
                    <li key={r.id}>
                      {r.date?.isoDate ?? "—"} · {r.merchant?.name ?? (isDe ? "Unbekannt" : "Unknown")} ·{" "}
                      {(r.totalAmount?.value ?? 0).toFixed(2)} €
                    </li>
                  ))}
                  {unreviewed.length > 3 && (
                    <li>{isDe ? `… und ${unreviewed.length - 3} weitere` : `… and ${unreviewed.length - 3} more`}</li>
                  )}
                </ul>
              </div>
            </div>
            <div className="flex shrink-0 flex-col items-stretch gap-2 sm:items-end">
              <Link
                href="/dashboard/activity"
                className="flex items-center justify-center gap-1.5 border border-black bg-white px-3.5 py-1.5 font-mono text-[11px] uppercase tracking-caps text-black hover:bg-[#F8FAFC]"
              >
                <UserCheck className="h-3.5 w-3.5" />
                <span>{isDe ? "Jetzt prüfen" : "Review Now"}</span>
              </Link>
              <button
                type="button"
                onClick={() => setTargetScope("VALIDATED")}
                className="border border-[#F59E0B] bg-white px-3.5 py-1.5 font-mono text-[11px] uppercase tracking-caps text-[#92400E] hover:bg-[#FEF3C7]"
              >
                {isDe ? "Nur geprüfte exportieren" : "Export only reviewed"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Rückfrage vor dem Export */}
      {pendingExport && (
        <div
          data-testid="export-confirm"
          className="border-2 border-black bg-white p-4"
        >
          <p className="text-sm font-bold text-black">
            {isDe
              ? `${unreviewed.length} von ${filteredReceipts.length} Belegen sind ungeprüft — trotzdem exportieren?`
              : `${unreviewed.length} of ${filteredReceipts.length} receipts are unreviewed — export anyway?`}
          </p>
          <p className="mt-1 text-xs text-[#475569]">
            {isDe ? "Ziel:" : "Target:"} {isDe ? EXPORT_LABELS[pendingExport].de : EXPORT_LABELS[pendingExport].en}
          </p>
          <div className="mt-3 flex flex-wrap items-center gap-2 font-mono text-[11px] uppercase tracking-caps">
            <button
              type="button"
              data-testid="export-confirm-yes"
              onClick={() => void runExport(pendingExport)}
              className="bg-black px-4 py-2 text-white hover:bg-[#334155]"
            >
              {isDe ? "Trotzdem exportieren" : "Export Anyway"}
            </button>
            <button
              type="button"
              data-testid="export-confirm-no"
              onClick={() => setPendingExport(null)}
              className="border border-[#E2E8F0] bg-white px-4 py-2 text-black hover:border-black"
            >
              {isDe ? "Abbrechen" : "Cancel"}
            </button>
          </div>
        </div>
      )}

      {/* Fehler / Hinweise aus dem Export */}
      {errorMessage && (
        <div
          data-testid="export-error"
          className="border border-[#BA1A1A] bg-[#FFDAD6] p-4 text-xs text-[#93000A]"
        >
          {errorMessage}
        </div>
      )}
      {warnings.length > 0 && (
        <ul
          data-testid="export-warnings"
          className="border border-[#F59E0B] bg-[#FEF3C7] p-4 space-y-1 text-[11px] text-[#78350F]"
        >
          {warnings.map((warning, index) => (
            <li key={index} className="flex items-start gap-2">
              <AlertTriangle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
              <span>{warning}</span>
            </li>
          ))}
        </ul>
      )}

      {/* Main 2-Column Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Left: PARAMETERS */}
        <div className="lg:col-span-5 space-y-6">
          <div className="bg-white border border-[#E2E8F0] p-6 space-y-6">
            <div className="flex items-center gap-2 pb-3 border-b border-[#E2E8F0]">
              <span className="w-2 h-2 bg-black"></span>
              <h2 className="font-mono text-xs font-bold uppercase tracking-caps text-black">
                PARAMETERS
              </h2>
            </div>

            {/* Zeitraum */}
            <div className="space-y-2">
              <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium">
                {isDe ? "ZEITRAUM (BELEGDATUM)" : "DATE RANGE (RECEIPT DATE)"}
              </label>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <span className="block font-mono text-[9px] text-[#94A3B8] uppercase">
                    {isDe ? "VON" : "FROM"}
                  </span>
                  <input
                    type="date"
                    value={startDate}
                    onChange={(e) => setStartDate(e.target.value)}
                    className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-1.5 font-mono text-xs text-black focus:border-black focus:outline-none"
                  />
                </div>
                <div>
                  <span className="block font-mono text-[9px] text-[#94A3B8] uppercase">
                    {isDe ? "BIS" : "TO"}
                  </span>
                  <input
                    type="date"
                    value={endDate}
                    onChange={(e) => setEndDate(e.target.value)}
                    className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-1.5 font-mono text-xs text-black focus:border-black focus:outline-none"
                  />
                </div>
              </div>
              <p className="font-mono text-[10px] text-[#94A3B8]">
                {isDe ? "Leer = alle Belege." : "Blank = all receipts."}
              </p>
            </div>

            {/* Umfang */}
            <div className="space-y-2 pt-2 border-t border-[#E2E8F0]">
              <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium">
                {isDe ? "UMFANG" : "SCOPE"}
              </label>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setTargetScope("ALL")}
                  className={`px-4 py-1.5 font-mono text-xs uppercase tracking-wider transition-colors ${
                    targetScope === "ALL"
                      ? "bg-black text-white font-bold"
                      : "bg-[#F8FAFC] border border-[#E2E8F0] text-[#475569] hover:text-black"
                  }`}
                >
                  {isDe ? `ALLE (${receipts.length})` : `ALL (${receipts.length})`}
                </button>
                <button
                  onClick={() => setTargetScope("VALIDATED")}
                  data-testid="scope-validated"
                  className={`px-4 py-1.5 font-mono text-xs uppercase tracking-wider transition-colors ${
                    targetScope === "VALIDATED"
                      ? "bg-black text-white font-bold"
                      : "bg-[#F8FAFC] border border-[#E2E8F0] text-[#475569] hover:text-black"
                  }`}
                >
                  {isDe ? "NUR GEPRÜFTE" : "REVIEWED ONLY"}
                </button>
              </div>
            </div>

            {/* Projekt / Ordner Filter */}
            <div className="space-y-2 pt-2 border-t border-[#E2E8F0]">
              <div className="flex items-center justify-between">
                <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium flex items-center gap-1.5">
                  <FolderKanban className="w-3.5 h-3.5" />
                  <span>{isDe ? "PROJEKT / ORDNER" : "PROJECT / FOLDER"}</span>
                </label>
                {!isPro && (
                  <span className="inline-flex items-center gap-1 text-[10px] font-mono text-[#94A3B8] uppercase">
                    <Lock className="w-3 h-3" />
                    <span>PRO</span>
                  </span>
                )}
              </div>
              <select
                data-testid="export-project-select"
                value={selectedProjectId}
                onChange={(e) => {
                  const val = e.target.value;
                  if (val && val !== "unassigned" && !isPro) {
                    openPaywall();
                    return;
                  }
                  setSelectedProjectId(val);
                }}
                className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-1.5 font-mono text-xs text-black focus:border-black focus:outline-none cursor-pointer"
              >
                <option value="">
                  {isDe ? `Alle Belege (${receipts.length})` : `All receipts (${receipts.length})`}
                </option>
                <option value="unassigned">
                  {isDe ? "Ohne Projekt" : "Unassigned"} (
                  {receipts.filter((r) => !r.projectId).length})
                </option>
                {projects.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name} ({receipts.filter((r) => r.projectId === p.id).length})
                  </option>
                ))}
              </select>
              {selectedProjectId && selectedProjectId !== "unassigned" && (
                <p className="font-mono text-[10px] text-blue-700 font-medium">
                  {isDe
                    ? `Filter aktiv: Nur Projekt „${projects.find((p) => p.id === selectedProjectId)?.name || selectedProjectId}“`
                    : `Filter active: Only project "${projects.find((p) => p.id === selectedProjectId)?.name || selectedProjectId}"`}
                </p>
              )}
            </div>

            {/* Payload */}
            <div className="p-5 bg-[#EEF4FC] border border-[#E2E8F0] space-y-1">
              <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B]">
                ESTIMATED PAYLOAD
              </span>
              <div className="font-display text-3xl font-bold text-black tracking-tight">
                {estimatedKb} <span className="text-base font-normal font-mono">KB</span>
              </div>
              <p className="font-mono text-[11px] text-[#475569]">
                {isDe
                  ? `${filteredReceipts.length} Belege im Filter`
                  : `${filteredReceipts.length} receipts in filter`}
                {unreviewed.length > 0 ? (isDe ? ` · ${unreviewed.length} ungeprüft` : ` · ${unreviewed.length} unreviewed`) : ""}
              </p>
            </div>

            {/* Aktionen */}
            <div className="pt-2 space-y-2">
              <button
                onClick={() => requestExport("xlsx")}
                disabled={isExporting || filteredReceipts.length === 0}
                data-testid="export-xlsx"
                className="w-full py-3 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors flex items-center justify-center gap-2 font-medium disabled:opacity-40"
              >
                <FileSpreadsheet className="w-4 h-4" />
                <span>{isDe ? "EXCEL HERUNTERLADEN (.XLSX)" : "DOWNLOAD EXCEL (.XLSX)"}</span>
              </button>

              <button
                onClick={() => requestExport("csv")}
                disabled={isExporting || filteredReceipts.length === 0}
                data-testid="export-csv"
                className="w-full py-3 bg-white border border-black text-black font-mono text-xs uppercase tracking-caps hover:bg-[#F8FAFC] transition-colors flex items-center justify-center gap-2 font-medium disabled:opacity-40"
              >
                <Download className="w-4 h-4" />
                <span>{isDe ? "CSV EXPORTIEREN" : "EXPORT CSV"}</span>
              </button>

              <button
                onClick={() => requestExport("pdf")}
                disabled={isExporting || filteredReceipts.length === 0}
                data-testid="export-pdf"
                className="w-full py-3 bg-white border border-black text-black font-mono text-xs uppercase tracking-caps hover:bg-[#F8FAFC] transition-colors flex items-center justify-center gap-2 font-medium disabled:opacity-40"
              >
                <FileDown className="w-4 h-4" />
                <span>{isDe ? "PDF-REPORT HERUNTERLADEN" : "DOWNLOAD PDF REPORT"}</span>
              </button>
            </div>
          </div>
        </div>

        {/* Right: SCHEMA PREVIEW */}
        <div className="lg:col-span-7 space-y-6">
          <div className="bg-white border border-[#E2E8F0] p-6 space-y-4">
            <div className="flex items-center justify-between pb-3 border-b border-[#E2E8F0]">
              <div className="flex items-center gap-2">
                <span className="w-2 h-2 bg-black"></span>
                <h2 className="font-mono text-xs font-bold uppercase tracking-caps text-black">
                  SCHEMA PREVIEW
                </h2>
              </div>
              <span className="font-mono text-[10px] bg-[#F8FAFC] border border-[#E2E8F0] px-2 py-0.5 text-[#64748B] uppercase">
                Sample: Top {Math.min(5, filteredReceipts.length)}
              </span>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left font-mono text-xs border-collapse">
                <thead>
                  <tr className="border-b border-[#E2E8F0] bg-[#F8FAFC] text-[#64748B] text-[10px] uppercase">
                    <th className="p-2.5">ID</th>
                    <th className="p-2.5">{isDe ? "BELEGDATUM" : "DATE"}</th>
                    <th className="p-2.5">MERCHANT / TYPE</th>
                    <th className="p-2.5">{isDe ? "PROJEKT" : "PROJECT"}</th>
                    <th className="p-2.5">{isDe ? "NETTO / BRUTTO" : "NET / GROSS"}</th>
                    <th className="p-2.5 text-right">STATUS</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#E2E8F0]">
                  {filteredReceipts.slice(0, 5).map((r, i) => {
                    const needsAttention = receiptNeedsAttention(r);
                    const projectName = r.projectId
                      ? projects.find((p) => p.id === r.projectId)?.name || "Projekt"
                      : null;
                    return (
                      <tr key={r.id || i} className="hover:bg-[#F8FAFC]">
                        <td className="p-2.5 text-black font-semibold">
                          NX_{String(i + 1).padStart(2, "0")}
                        </td>
                        <td className="p-2.5 text-[#475569]">{r.date?.isoDate ?? "—"}</td>
                        <td className="p-2.5 text-black font-medium truncate max-w-[120px]">
                          {r.merchant?.name ?? "—"}
                        </td>
                        <td className="p-2.5 text-[#64748B]">
                          {projectName ? (
                            <span className="bg-[#F1F5F9] border border-[#E2E8F0] px-1.5 py-0.5 text-[10px] text-black">
                              {projectName}
                            </span>
                          ) : (
                            <span className="text-[#CBD5E1] text-[10px]">—</span>
                          )}
                        </td>
                        <td className="p-2.5 text-[#475569]">
                          {(r.netAmount ?? 0).toFixed(2)}€ /{" "}
                          {(r.totalAmount?.value ?? 0).toFixed(2)}€
                        </td>
                        <td className="p-2.5 text-right">
                          {needsAttention ? (
                            <span className="inline-flex items-center gap-1 text-[#92400E] font-bold text-[11px]">
                              <AlertTriangle className="w-3 h-3" />
                              <span>{isDe ? "PRÜFEN" : "REVIEW"}</span>
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-emerald-600 font-bold text-[11px]">
                              <CheckCircle2 className="w-3 h-3" />
                              <span>OK</span>
                            </span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                  {filteredReceipts.length === 0 && (
                    <tr>
                      <td
                        colSpan={6}
                        className="p-6 text-center text-[#94A3B8] font-mono text-xs"
                      >
                        {isDe ? "Keine Belege im aktuellen Filter." : "No receipts found for current filter."}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>

            <div className="pt-4 border-t border-[#E2E8F0] flex flex-wrap items-center justify-between gap-2 text-[10px] font-mono text-[#94A3B8] uppercase">
              <span>SCHEMA VERSION: 1.4 / STRICT MODE ENABLED</span>
              <span>{isDe ? `${filteredReceipts.length} BELEGE IM FILTER` : `${filteredReceipts.length} RECEIPTS IN FILTER`}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
