"use client";

import React, { useEffect, useMemo, useState, useRef, useCallback } from "react";
import { useI18n } from "@/lib/i18n/context";
import {
  DocumentType,
  grossWithTip,
  PaymentMethod,
  ProcessedReceipt,
  ReceiptCategory,
  ReceiptData,
  TaxBreakdownItem,
  ValidationIssue,
} from "@/lib/schema/receipt";
import {
  EditedReceiptField,
  confirmReceiptReviewed,
  recalculateReceipt,
  receiptNeedsAttention,
} from "@/lib/ai/recalculate";
import { CONFIDENCE_THRESHOLDS } from "@/lib/ai/mathValidator";

import {
  formatAmountInput,
  formatMoney,
  grossOf,
  netOf,
  parseAmountInput,
  receiptCurrency,
} from "./receiptFormat";
import { DocumentViewer } from "./DocumentViewer";
import { LineItemsEditor } from "./LineItemsEditor";
import { TaxBreakdownEditor } from "./TaxBreakdownEditor";
import {
  X,
  Building2,
  Calendar,
  Tag,
  Receipt,
  Save,
  UserCheck,
  CreditCard,
  RotateCcw,
  ChevronLeft,
  ChevronRight,
  Clock,
  Sparkles,
  Edit3,
  CheckCircle2,
  AlertTriangle,
  FileText,
  Users,
  Image as ImageIcon,
} from "lucide-react";

export interface ReceiptInspectorModalProps {
  receipt: ProcessedReceipt | null;
  isOpen?: boolean;
  onClose: () => void;
  onSave?: (updated: ProcessedReceipt) => void;
  onNavigate?: (direction: "prev" | "next") => void;
  currentIndex?: number;
  totalCount?: number;
  /** Server-seitiges Persistieren (PostgreSQL) statt IndexedDB. */
  onPersist?: (updated: ProcessedReceipt) => Promise<void>;
}

const CATEGORIES: ReceiptCategory[] = [
  "Bewirtung",
  "Reisekosten & Hotel",
  "Tanken & KFZ",
  "Bürobedarf & IT",
  "Verpflegungsmehraufwand",
  "Material & Einkauf",
  "Sonstiges",
];

const CATEGORY_LABELS: Record<ReceiptCategory, { de: string; en: string }> = {
  "Bewirtung": { de: "Bewirtung", en: "Meals & Entertainment" },
  "Reisekosten & Hotel": { de: "Reisekosten & Hotel", en: "Travel & Lodging" },
  "Tanken & KFZ": { de: "Tanken & KFZ", en: "Fuel & Vehicle" },
  "Bürobedarf & IT": { de: "Bürobedarf & IT", en: "Office Supplies & IT" },
  "Verpflegungsmehraufwand": { de: "Verpflegungsmehraufwand", en: "Per Diem / Subsistence" },
  "Material & Einkauf": { de: "Material & Einkauf", en: "Supplies & Inventory" },
  "Sonstiges": { de: "Sonstiges", en: "Other / Misc" },
};

const DOC_TYPES: DocumentType[] = [
  "KASSENBON",
  "RECHNUNG",
  "TANKBELEG",
  "BEWIRTUNGSBELEG",
  "PARKTICKET",
  "SONSTIGES",
];

const DOC_TYPE_LABELS: Record<DocumentType, { de: string; en: string }> = {
  "KASSENBON": { de: "KASSENBON", en: "RECEIPT" },
  "RECHNUNG": { de: "RECHNUNG", en: "INVOICE" },
  "TANKBELEG": { de: "TANKBELEG", en: "FUEL TICKET" },
  "BEWIRTUNGSBELEG": { de: "BEWIRTUNGSBELEG", en: "RESTAURANT RECEIPT" },
  "PARKTICKET": { de: "PARKTICKET", en: "PARKING TICKET" },
  "SONSTIGES": { de: "SONSTIGES", en: "OTHER" },
};

const PAYMENT_METHODS: { value: PaymentMethod; labelDe: string; labelEn: string }[] = [
  { value: "EC_KARTE", labelDe: "EC-Karte / Girocard", labelEn: "Debit Card / Girocard" },
  { value: "KREDITKARTE", labelDe: "Kreditkarte", labelEn: "Credit Card" },
  { value: "BAR", labelDe: "Barzahlung", labelEn: "Cash" },
  { value: "UEBERWEISUNG", labelDe: "Überweisung", labelEn: "Bank Transfer" },
  { value: "PAYPAL", labelDe: "PayPal", labelEn: "PayPal" },
  { value: "APPLE_PAY", labelDe: "Apple Pay", labelEn: "Apple Pay" },
  { value: "GOOGLE_PAY", labelDe: "Google Pay", labelEn: "Google Pay" },
  { value: "SONSTIGE", labelDe: "Sonstige", labelEn: "Other" },
];

const inputClass =
  "w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-2 text-sm text-black focus:border-black focus:bg-white focus:outline-none transition-colors";
const labelClass =
  "text-[10px] font-mono uppercase tracking-caps font-semibold text-[#475569] block mb-1";

function issuesOf(receipt: ProcessedReceipt | null): ValidationIssue[] {
  const issues = receipt?.validation?.issues;
  if (Array.isArray(issues)) {
    const usable = issues.filter(
      (issue): issue is ValidationIssue =>
        !!issue && typeof issue.message === "string" && issue.message.length > 0
    );
    if (usable.length > 0) {
      return [
        ...usable.filter((issue) => issue.severity === "error"),
        ...usable.filter((issue) => issue.severity !== "error"),
      ];
    }
  }
  const legacyReason = receipt?.validation?.reviewReason;
  if (legacyReason) {
    return [
      {
        field: "none",
        severity: receipt?.validation?.isMathValid === false ? "error" : "warning",
        message: legacyReason,
      },
    ];
  }
  return [];
}

export function ReceiptInspectorModal({
  receipt,
  isOpen = true,
  onClose,
  onSave,
  onNavigate,
  currentIndex,
  totalCount,
  onPersist,
}: ReceiptInspectorModalProps) {
  const { t, language } = useI18n();
  const isDe = language === "de";

  const persist = useCallback(
    async (updated: ProcessedReceipt) => {
      if (onPersist) await onPersist(updated);
    },
    [onPersist]
  );

  const [formData, setFormData] = useState<ProcessedReceipt | null>(receipt);
  const [activeHighlightField, setActiveHighlightField] = useState<string | null>(null);
  const [saveStatus, setSaveStatus] = useState<"saved" | "saving" | "idle">("idle");
  const [mobileTab, setMobileTab] = useState<"doc" | "data">("data");
  const [editedFieldsSet, setEditedFieldsSet] = useState<Set<string>>(new Set());

  const autoSaveTimerRef = useRef<NodeJS.Timeout | null>(null);

  // Initialize and synchronize receipt state
  useEffect(() => {
    if (receipt) {
      // Capture original extraction snapshot for 1-click revert if not present
      const originalExtraction = receipt.originalExtraction || {
        merchant: receipt.merchant,
        date: receipt.date,
        totalAmount: receipt.totalAmount,
        netAmount: receipt.netAmount,
        tipAmount: receipt.tipAmount,
        taxBreakdown: receipt.taxBreakdown,
        lineItems: receipt.lineItems,
        suggestedCategory: receipt.suggestedCategory,
        documentType: receipt.documentType,
        receiptNumber: receipt.receiptNumber,
      };

      const initialEdited = new Set<string>();
      if (Array.isArray(receipt.editedFields)) {
        receipt.editedFields.forEach((f) => initialEdited.add(f));
      } else if (receipt.editedFields && typeof receipt.editedFields === "object") {
        Object.keys(receipt.editedFields).forEach((f) => initialEdited.add(f));
      }

      setFormData({
        ...receipt,
        originalExtraction,
      });
      setEditedFieldsSet(initialEdited);
      setSaveStatus("idle");
    } else {
      setFormData(null);
    }
  }, [receipt]);

  // Keyboard navigation shortcuts (Alt + ArrowLeft/Right, Escape)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.altKey && e.key === "ArrowLeft") {
        e.preventDefault();
        onNavigate?.("prev");
      } else if (e.altKey && e.key === "ArrowRight") {
        e.preventDefault();
        onNavigate?.("next");
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose, onNavigate]);

  const issues = useMemo(() => issuesOf(formData), [formData]);

  if (!isOpen || !receipt || !formData) return null;

  const currency = receiptCurrency(formData);
  const needsAttention = receiptNeedsAttention(formData);
  const errorCount = issues.filter((issue) => issue.severity === "error").length;

  /** Apply mutation, recalculate math, track edited field, and trigger debounced auto-save */
  const applyEdit = (
    mutate: (draft: ProcessedReceipt) => ProcessedReceipt,
    fieldKey: string,
    editedField: EditedReceiptField = "none"
  ) => {
    const nextEdited = new Set(editedFieldsSet);
    nextEdited.add(fieldKey);
    setEditedFieldsSet(nextEdited);

    setFormData((prev) => {
      if (!prev) return null;
      const mutated = mutate(prev);
      const recalculated = recalculateReceipt(mutated, { editedField });
      const updated: ProcessedReceipt = {
        ...recalculated,
        editedFields: Array.from(nextEdited),
        updatedAt: new Date().toISOString(),
      };

      // Debounced background auto-save
      setSaveStatus("saving");
      if (autoSaveTimerRef.current) clearTimeout(autoSaveTimerRef.current);
      autoSaveTimerRef.current = setTimeout(async () => {
        try {
          await persist(updated);
          setSaveStatus("saved");
          onSave?.(updated);
        } catch {
          setSaveStatus("idle");
        }
      }, 400);

      return updated;
    });
  };

  /** Revert a single field to original AI extraction value */
  const revertField = (fieldKey: string) => {
    const original = formData.originalExtraction;
    if (!original) return;

    const nextEdited = new Set(editedFieldsSet);
    nextEdited.delete(fieldKey);
    setEditedFieldsSet(nextEdited);

    setFormData((prev) => {
      if (!prev) return null;
      let next = { ...prev };

      if (fieldKey === "merchant" && original.merchant) {
        next.merchant = { ...original.merchant };
      } else if (fieldKey === "date" && original.date) {
        next.date = { ...original.date };
      } else if (fieldKey === "receiptNumber") {
        next.receiptNumber = original.receiptNumber ?? null;
      } else if (fieldKey === "suggestedCategory" && original.suggestedCategory) {
        next.suggestedCategory = original.suggestedCategory;
      } else if (fieldKey === "documentType" && original.documentType) {
        next.documentType = original.documentType;
      } else if (fieldKey === "totalAmount" && original.totalAmount) {
        next.totalAmount = { ...original.totalAmount };
      } else if (fieldKey === "netAmount") {
        next.netAmount = original.netAmount ?? null;
      } else if (fieldKey === "tipAmount") {
        next.tipAmount = original.tipAmount ?? null;
      } else if (fieldKey === "taxBreakdown" && original.taxBreakdown) {
        next.taxBreakdown = [...original.taxBreakdown];
      } else if (fieldKey === "lineItems" && original.lineItems) {
        next.lineItems = [...original.lineItems];
      }

      const recalculated = recalculateReceipt(next, { editedField: "none" });
      const updated: ProcessedReceipt = {
        ...recalculated,
        editedFields: Array.from(nextEdited),
        updatedAt: new Date().toISOString(),
      };

      persist(updated).then(() => {
        setSaveStatus("saved");
        onSave?.(updated);
      });

      return updated;
    });
  };

  /** Commits financial amount inputs */
  const commitGross = (raw: string) => {
    const parsed = parseAmountInput(raw);
    if (parsed === null || parsed === grossOf(formData)) return;
    applyEdit(
      (prev) => ({ ...prev, totalAmount: { ...prev.totalAmount, value: parsed } }),
      "totalAmount",
      "totalAmount"
    );
  };

  const commitNet = (raw: string) => {
    const parsed = parseAmountInput(raw);
    if (parsed === null && formData.netAmount === null) return;
    if (parsed !== null && parsed === formData.netAmount) return;
    applyEdit(
      (prev) => ({ ...prev, netAmount: parsed }),
      "netAmount",
      "netAmount"
    );
  };

  /**
   * Trinkgeld geht bewusst NICHT durch recalculateReceipt: Es traegt keine MwSt
   * und darf Brutto, Netto und Steueraufteilung nicht veraendern.
   */
  const commitTip = (raw: string) => {
    const parsed = parseAmountInput(raw);
    const current = formData.tipAmount ?? null;
    const normalized = parsed === 0 ? null : parsed;
    if (normalized === current) return;
    applyEdit(
      (prev) => ({ ...prev, tipAmount: normalized }),
      "tipAmount",
      "none"
    );
  };

  const commitTaxRows = (
    next: TaxBreakdownItem[],
    opts?: { recomputeFromGross?: boolean }
  ) => {
    applyEdit(
      (prev) => {
        const previous = prev.taxBreakdown ?? [];
        let lineItems = prev.lineItems;
        if (previous.length === next.length) {
          const remaps = previous
            .map((old, i) => ({ from: old.ratePercent, to: next[i]?.ratePercent }))
            .filter((pair) => pair.to !== undefined && pair.from !== pair.to);
          if (remaps.length === 1) {
            const { from, to } = remaps[0];
            lineItems = (prev.lineItems ?? []).map((item) =>
              item.taxRate === from ? { ...item, taxRate: to } : item
            );
          }
        }
        return { ...prev, taxBreakdown: next, lineItems };
      },
      "taxBreakdown",
      opts?.recomputeFromGross ? "totalAmount" : "taxBreakdown"
    );
  };

  /** Explicit save and close */
  const handleSave = async () => {
    const updated: ProcessedReceipt = {
      ...formData,
      editedFields: Array.from(editedFieldsSet),
      updatedAt: new Date().toISOString(),
    };
    await persist(updated);
    onSave?.(updated);
    onClose();
  };

  /** Explicit save confirmed and close */
  const handleSaveConfirmed = async () => {
    const confirmed = confirmReceiptReviewed(formData);
    const updated: ProcessedReceipt = {
      ...confirmed,
      editedFields: Array.from(editedFieldsSet),
      updatedAt: new Date().toISOString(),
    };
    await persist(updated);
    onSave?.(updated);
    onClose();
  };

  /** Renders an audit badge showing AI Extracted vs Manually Edited with 1-click revert */
  const renderAuditBadge = (fieldKey: string, confidence: number = 1.0) => {
    const isEdited = editedFieldsSet.has(fieldKey);
    const confPct = Math.round((confidence || 1) * 100);

    if (isEdited) {
      return (
        <span className="inline-flex items-center gap-1">
          <span
            data-testid={`badge-edited-${fieldKey}`}
            className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-[#EEF4FC] text-[#0066FF] border border-[#0066FF]/30 font-mono text-[9px] uppercase tracking-caps font-semibold"
          >
            <Edit3 className="w-2.5 h-2.5" />
            <span>{isDe ? "Bearbeitet" : "Edited"}</span>
          </span>
          <button
            type="button"
            data-testid={`revert-${fieldKey}`}
            onClick={() => revertField(fieldKey)}
            title={isDe ? "Auf ursprünglichen KI-Wert zurücksetzen" : "Reset to original AI extraction"}
            className="p-0.5 text-slate-400 hover:text-black hover:bg-slate-100 transition-colors"
          >
            <RotateCcw className="w-2.5 h-2.5" />
          </button>
        </span>
      );
    }

    return (
      <span
        data-testid={`badge-ai-${fieldKey}`}
        className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-[#F1F5F9] text-[#475569] border border-[#CBD5E1] font-mono text-[9px] uppercase tracking-caps"
      >
        <Sparkles className="w-2.5 h-2.5 text-slate-500" />
        <span>{confPct}% {isDe ? "KI" : "AI"}</span>
      </span>
    );
  };

  return (
    <div
      data-testid="receipt-inspector-modal"
      className="fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-4 bg-black/70 backdrop-blur-sm animate-fade-in font-sans"
    >
      <div className="relative w-full max-w-7xl h-[94vh] flex flex-col bg-white border-2 border-black shadow-2xl overflow-hidden">
        {/* Modal Top Header */}
        <div className="flex items-center justify-between border-b border-[#E2E8F0] bg-white px-4 py-3 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-black text-white flex items-center justify-center shrink-0">
              <Receipt className="h-4 w-4" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="text-base font-display font-bold text-black tracking-tight">
                  {isDe ? "Inspektor & Split-Review" : "Inspector & Split Review"}
                </h3>
                <span
                  data-testid="modal-status"
                  className={`inline-flex items-center gap-1 px-2 py-0.5 font-mono text-[10px] uppercase tracking-caps ${
                    needsAttention
                      ? "bg-[#FEF3C7] text-[#92400E] border border-[#F59E0B]"
                      : formData.validation?.userConfirmed
                        ? "bg-[#EEF4FC] text-[#334155] border border-[#CBD5E1]"
                        : "bg-emerald-50 text-emerald-800 border border-emerald-200"
                  }`}
                >
                  {needsAttention ? (
                    <>
                      <AlertTriangle className="w-3 h-3 text-[#D97706]" />
                      <span>
                        {errorCount} {isDe ? "Fehler" : "Errors"} · {issues.length - errorCount} {isDe ? "Hinweise" : "Warnings"}
                      </span>
                    </>
                  ) : (
                    <>
                      <CheckCircle2 className="w-3 h-3 text-emerald-600" />
                      <span>{formData.validation?.userConfirmed ? (isDe ? "Bestätigt" : "Confirmed") : (isDe ? "Gültig" : "Valid")}</span>
                    </>
                  )}
                </span>
              </div>
              <p className="text-xs text-[#64748B] font-mono truncate max-w-md">
                ID: {formData.id} • {formData.originalFileName || (isDe ? "Scan" : "Scan")}
              </p>
            </div>
          </div>

          {/* Navigation & Actions */}
          <div className="flex items-center gap-2">
            {/* Prev / Next Navigation */}
            {onNavigate && (
              <div className="flex items-center border border-[#E2E8F0] bg-[#F8FAFC]">
                <button
                  type="button"
                  data-testid="nav-prev-btn"
                  onClick={() => onNavigate("prev")}
                  className="p-1.5 text-black hover:bg-white transition-colors"
                  title={isDe ? "Vorheriger Beleg (Alt + ←)" : "Previous Receipt (Alt + ←)"}
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                {typeof currentIndex === "number" && typeof totalCount === "number" && (
                  <span
                    data-testid="nav-counter"
                    className="px-2 font-mono text-[11px] text-[#475569] uppercase tracking-caps"
                  >
                    {currentIndex + 1} / {totalCount}
                  </span>
                )}
                <button
                  type="button"
                  data-testid="nav-next-btn"
                  onClick={() => onNavigate("next")}
                  className="p-1.5 text-black hover:bg-white transition-colors"
                  title={isDe ? "Nächster Beleg (Alt + →)" : "Next Receipt (Alt + →)"}
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            )}

            <button
              onClick={onClose}
              data-testid="modal-close-btn"
              className="p-1.5 border border-[#E2E8F0] hover:border-black text-black hover:bg-[#F8FAFC] transition-colors ml-1"
              aria-label="Close"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        </div>

        {/* Mobile Tab Toggle (< 768px) */}
        <div className="md:hidden flex border-b border-[#E2E8F0] bg-[#F8FAFC] shrink-0 font-mono text-xs uppercase tracking-caps">
          <button
            type="button"
            data-testid="mobile-tab-doc"
            onClick={() => setMobileTab("doc")}
            className={`flex-1 py-2 text-center flex items-center justify-center gap-1.5 border-r border-[#E2E8F0] ${
              mobileTab === "doc"
                ? "bg-white text-black font-bold border-b-2 border-b-black"
                : "text-[#64748B]"
            }`}
          >
            <ImageIcon className="w-3.5 h-3.5" />
            <span>{isDe ? "Beleg-Bild" : "Receipt Image"}</span>
          </button>
          <button
            type="button"
            data-testid="mobile-tab-data"
            onClick={() => setMobileTab("data")}
            className={`flex-1 py-2 text-center flex items-center justify-center gap-1.5 ${
              mobileTab === "data"
                ? "bg-white text-black font-bold border-b-2 border-b-black"
                : "text-[#64748B]"
            }`}
          >
            <FileText className="w-3.5 h-3.5" />
            <span>{isDe ? "Extrahierte Daten" : "Extracted Data"}</span>
          </button>
        </div>

        {/* 50/50 Dual-Pane Split Body */}
        <div className="flex-1 grid grid-cols-1 md:grid-cols-2 overflow-hidden">
          {/* LEFT PANE: DocumentViewer (Zoom / Pan / Rotate / Bounding Boxes) */}
          <div
            className={`h-full border-r border-[#E2E8F0] overflow-hidden ${
              mobileTab === "doc" ? "block" : "hidden md:block"
            }`}
          >
            <DocumentViewer
              previewUrl={formData.previewUrl}
              fileName={formData.originalFileName}
              receiptId={formData.id}
              boundingBoxes={formData.boundingBoxes}
              activeHighlightField={activeHighlightField}
              onSelectField={(fieldKey) => setActiveHighlightField(fieldKey)}
            />
          </div>

          {/* RIGHT PANE: Extracted Data & Editable Fields */}
          <div
            className={`h-full overflow-y-auto p-4 sm:p-6 space-y-5 bg-[#FAFCFF] ${
              mobileTab === "data" ? "block" : "hidden md:block"
            }`}
          >
            {/* Issues Alert Box */}
            {issues.length > 0 && (
              <div
                data-testid="modal-issue-list"
                className="space-y-1.5 border border-[#F59E0B] bg-[#FEF3C7] p-3"
              >
                <div className="flex items-center gap-1.5 font-mono text-xs font-bold text-[#92400E] uppercase tracking-caps mb-1">
                  <AlertTriangle className="w-3.5 h-3.5" />
                  <span>{isDe ? "Validierungsbefunde" : "Validation Findings"} ({issues.length})</span>
                </div>
                {issues.map((issue, index) => (
                  <div key={index} className="flex items-start gap-2 text-xs">
                    <span
                      className={`mt-0.5 shrink-0 px-1.5 py-0.2 font-mono text-[9px] uppercase ${
                        issue.severity === "error"
                          ? "bg-[#FFDAD6] text-[#93000A]"
                          : "bg-[#FDE68A] text-[#92400E]"
                      }`}
                    >
                      {issue.severity === "error" ? (isDe ? "Fehler" : "Error") : (isDe ? "Hinweis" : "Warning")}
                    </span>
                    <span className="text-black">{issue.message}</span>
                  </div>
                ))}
              </div>
            )}

            {/* Section 1: Händler & Kategorie */}
            <div className="bg-white border border-[#E2E8F0] p-4 space-y-3">
              <h4 className="font-mono text-xs uppercase tracking-caps font-bold text-black border-b border-[#E2E8F0] pb-1.5 flex items-center justify-between">
                <span>{isDe ? "Händler & Kategorie" : "Merchant & Category"}</span>
                {renderAuditBadge("merchant", formData.merchant?.confidence)}
              </h4>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className={labelClass}>{isDe ? "Händler / Aussteller" : "Merchant / Issuer"}</label>
                  <div className="relative">
                    <Building2 className="absolute left-3 top-2.5 h-4 w-4 text-[#94A3B8]" />
                    <input
                      type="text"
                      data-testid="modal-merchant"
                      value={formData.merchant?.name ?? ""}
                      onFocus={() => setActiveHighlightField("merchant")}
                      onChange={(e) =>
                        applyEdit(
                          (prev) => ({
                            ...prev,
                            merchant: { ...prev.merchant, name: e.target.value },
                          }),
                          "merchant",
                          "merchant"
                        )
                      }
                      className={`${inputClass} pl-9 ${
                        (formData.merchant?.confidence ?? 1) <
                        CONFIDENCE_THRESHOLDS.merchant
                          ? "bg-amber-50"
                          : ""
                      }`}
                    />
                  </div>
                </div>

                <div>
                  <label className={labelClass}>{isDe ? "Kategorie" : "Category"}</label>
                  <div className="relative">
                    <Tag className="absolute left-3 top-2.5 h-4 w-4 text-[#94A3B8]" />
                    <select
                      data-testid="modal-category"
                      value={formData.suggestedCategory}
                      onFocus={() => setActiveHighlightField("category")}
                      onChange={(e) =>
                        applyEdit(
                          (prev) => ({
                            ...prev,
                            suggestedCategory: e.target.value as ReceiptCategory,
                          }),
                          "suggestedCategory",
                          "category"
                        )
                      }
                      className={`${inputClass} pl-9`}
                    >
                      {CATEGORIES.map((c) => (
                        <option key={c} value={c}>
                          {isDe ? CATEGORY_LABELS[c]?.de || c : CATEGORY_LABELS[c]?.en || c}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>
            </div>

            {/* Section 2: Datum & Belegdaten */}
            <div className="bg-white border border-[#E2E8F0] p-4 space-y-3">
              <h4 className="font-mono text-xs uppercase tracking-caps font-bold text-black border-b border-[#E2E8F0] pb-1.5 flex items-center justify-between">
                <span>{isDe ? "Datum & Belegdaten" : "Date & Receipt Info"}</span>
                {renderAuditBadge("date", formData.date?.confidence)}
              </h4>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className={labelClass}>{isDe ? "Belegdatum" : "Receipt Date"}</label>
                  <div className="relative">
                    <Calendar className="absolute left-3 top-2.5 h-4 w-4 text-[#94A3B8]" />
                    <input
                      type="date"
                      data-testid="modal-date"
                      value={formData.date?.isoDate ?? ""}
                      onFocus={() => setActiveHighlightField("date")}
                      onChange={(e) =>
                        applyEdit(
                          (prev) => ({
                            ...prev,
                            date: { ...prev.date, isoDate: e.target.value },
                          }),
                          "date",
                          "date"
                        )
                      }
                      className={`${inputClass} pl-9 font-mono ${
                        (formData.date?.confidence ?? 1) < CONFIDENCE_THRESHOLDS.date
                          ? "bg-amber-50"
                          : ""
                      }`}
                    />
                  </div>
                </div>

                <div>
                  <label className={labelClass}>{isDe ? "Belegart" : "Document Type"}</label>
                  <select
                    data-testid="modal-doctype"
                    value={formData.documentType}
                    onFocus={() => setActiveHighlightField("documentType")}
                    onChange={(e) =>
                      applyEdit(
                        (prev) => ({
                          ...prev,
                          documentType: e.target.value as DocumentType,
                        }),
                        "documentType",
                        "none"
                      )
                    }
                    className={`${inputClass} font-mono text-xs uppercase`}
                  >
                    {DOC_TYPES.map((type) => (
                      <option key={type} value={type}>
                        {isDe ? DOC_TYPE_LABELS[type]?.de || type : DOC_TYPE_LABELS[type]?.en || type}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className={labelClass}>{isDe ? "Belegnummer" : "Receipt Number"}</label>
                  <input
                    type="text"
                    data-testid="modal-receipt-number"
                    value={formData.receiptNumber || ""}
                    placeholder={isDe ? "z.B. RE-10492" : "e.g. INV-10492"}
                    onFocus={() => setActiveHighlightField("receiptNumber")}
                    onChange={(e) =>
                      applyEdit(
                        (prev) => ({
                          ...prev,
                          receiptNumber: e.target.value.trim() === "" ? null : e.target.value,
                        }),
                        "receiptNumber",
                        "none"
                      )
                    }
                    className={`${inputClass} font-mono`}
                  />
                </div>
              </div>
            </div>

            {/* Section 3: Zahlungsart */}
            <div className="bg-white border border-[#E2E8F0] p-4 space-y-3">
              <h4 className="font-mono text-xs uppercase tracking-caps font-bold text-black border-b border-[#E2E8F0] pb-1.5 flex items-center justify-between">
                <span>{isDe ? "Zahlungsart" : "Payment Method"}</span>
                {renderAuditBadge("paymentMethod", 1.0)}
              </h4>

              <div className="relative">
                <CreditCard className="absolute left-3 top-2.5 h-4 w-4 text-[#94A3B8]" />
                <select
                  data-testid="modal-payment-method"
                  value={formData.paymentMethod || "EC_KARTE"}
                  onFocus={() => setActiveHighlightField("paymentMethod")}
                  onChange={(e) =>
                    applyEdit(
                      (prev) => ({
                        ...prev,
                        paymentMethod: e.target.value as PaymentMethod,
                      }),
                      "paymentMethod",
                      "none"
                    )
                  }
                  className={`${inputClass} pl-9 font-mono`}
                >
                  {PAYMENT_METHODS.map((pm) => (
                    <option key={pm.value} value={pm.value}>
                      {isDe ? pm.labelDe : pm.labelEn}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Section 4: Beträge & Steuern */}
            <div className="bg-white border border-[#E2E8F0] p-4 space-y-3">
              <h4 className="font-mono text-xs uppercase tracking-caps font-bold text-black border-b border-[#E2E8F0] pb-1.5 flex items-center justify-between">
                <span>{isDe ? "Beträge & Steuern" : "Amounts & Taxes"}</span>
                {renderAuditBadge("totalAmount", formData.totalAmount?.confidence)}
              </h4>

              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                <AmountField
                  label={`${isDe ? "Brutto Gesamt" : "Gross Total"} (${currency})`}
                  value={formatAmountInput(grossOf(formData))}
                  testId="modal-gross"
                  strong
                  highlight={
                    (formData.totalAmount?.confidence ?? 1) <
                    CONFIDENCE_THRESHOLDS.totalAmount
                  }
                  onFocus={() => setActiveHighlightField("totalAmount")}
                  onCommit={commitGross}
                />
                <AmountField
                  label={`${isDe ? "Netto" : "Net"} (${currency})`}
                  value={formatAmountInput(netOf(formData))}
                  testId="modal-net"
                  onFocus={() => setActiveHighlightField("netAmount")}
                  onCommit={commitNet}
                />
                <AmountField
                  label={`${isDe ? "Trinkgeld" : "Tip"} (${currency})`}
                  value={formatAmountInput(formData.tipAmount ?? null)}
                  testId="modal-tip"
                  placeholder="—"
                  onFocus={() => setActiveHighlightField("totalAmount")}
                  onCommit={commitTip}
                />
              </div>

              <TaxBreakdownEditor
                taxes={formData.taxBreakdown ?? []}
                currency={currency}
                activeHighlightField={activeHighlightField}
                onSelectField={(fieldKey) => setActiveHighlightField(fieldKey)}
                onChange={commitTaxRows}
              />

              {(formData.tipAmount ?? 0) > 0 && (
                <div className="flex items-center justify-between font-mono text-xs pt-2">
                  <span className="text-[#64748B]">
                    {isDe ? "Gesamt gezahlt (inkl. Trinkgeld):" : "Total paid (incl. tip):"}
                  </span>
                  <span className="font-bold text-black" data-testid="modal-paid-total">
                    {formatMoney(grossWithTip(formData), currency)}
                  </span>
                </div>
              )}

              <div className="flex items-center justify-between font-mono text-xs pt-2 border-t border-[#E2E8F0]">
                <span className="text-[#64748B]">{isDe ? "Summe Steuer:" : "Total Tax:"}</span>
                <span className="font-bold text-black">
                  {formatMoney(
                    (formData.taxBreakdown ?? []).reduce(
                      (acc, item) => acc + (item?.taxAmount ?? 0),
                      0
                    ),
                    currency
                  )}
                </span>
              </div>
            </div>

            {/* Section 5: Einzelpositionen (LineItemsEditor) */}
            <div className="bg-white border border-[#E2E8F0] p-4">
              <LineItemsEditor
                items={formData.lineItems || []}
                currency={currency}
                totalGross={grossOf(formData)}
                activeHighlightField={activeHighlightField}
                onSelectField={(fieldKey) => setActiveHighlightField(fieldKey)}
                onChange={(updatedItems) => {
                  applyEdit(
                    (prev) => ({ ...prev, lineItems: updatedItems }),
                    "lineItems",
                    "lineItems"
                  );
                }}
              />
            </div>
          </div>
        </div>

        {/* Modal Sticky Footer */}
        <div className="border-t border-[#E2E8F0] bg-[#F8FAFC] px-4 sm:px-6 py-3 flex flex-wrap items-center justify-between gap-3 shrink-0 font-mono text-xs">
          {/* Status Feedback Indicator */}
          <div className="flex items-center gap-2" data-testid="auto-save-status">
            <span
              className={`w-2 h-2 rounded-full ${
                saveStatus === "saving"
                  ? "bg-amber-400 animate-ping"
                  : "bg-emerald-500"
              }`}
            />
            <span className="text-[#475569] text-[11px]">
              {saveStatus === "saving"
                ? (isDe ? "◌ Speichere Änderungen..." : "◌ Saving changes...")
                : (isDe ? "● Gespeichert" : "● Saved")}
            </span>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-white border border-[#E2E8F0] hover:border-black text-black uppercase tracking-caps transition-colors"
            >
              {isDe ? (t.modal?.close || "Schließen") : "Close"}
            </button>
            {needsAttention && (
              <button
                type="button"
                onClick={handleSaveConfirmed}
                data-testid="modal-save-confirmed"
                className="inline-flex items-center gap-1.5 px-4 py-2 bg-white border border-black text-black hover:bg-[#EEF4FC] uppercase tracking-caps transition-colors"
              >
                <UserCheck className="h-3.5 w-3.5" />
                <span>{isDe ? "Als geprüft markieren" : "Mark as Reviewed"}</span>
              </button>
            )}
            <button
              type="button"
              onClick={handleSave}
              data-testid="modal-save"
              className="inline-flex items-center gap-1.5 px-5 py-2 bg-black text-white hover:bg-[#334155] uppercase tracking-caps font-medium transition-colors"
            >
              <Save className="h-3.5 w-3.5" />
              <span>{isDe ? "Änderungen speichern" : "Save Changes"}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

interface AmountFieldProps {
  label: string;
  value: string;
  testId?: string;
  placeholder?: string;
  strong?: boolean;
  highlight?: boolean;
  onFocus?: () => void;
  onCommit: (raw: string) => void;
}

function AmountField({
  label,
  value,
  testId,
  placeholder,
  strong = false,
  highlight = false,
  onFocus,
  onCommit,
}: AmountFieldProps) {
  const [draft, setDraft] = useState(value);
  const [dirty, setDirty] = useState(false);

  if (!dirty && draft !== value) {
    setDraft(value);
  }

  const commit = () => {
    setDirty(false);
    if (draft !== value) onCommit(draft);
  };

  return (
    <label className="block">
      <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block mb-1">
        {label}
      </span>
      <input
        type="text"
        inputMode="decimal"
        value={draft}
        data-testid={testId}
        placeholder={placeholder}
        onFocus={onFocus}
        onChange={(event) => {
          setDirty(true);
          setDraft(event.target.value);
        }}
        onBlur={commit}
        onKeyDown={(event) => {
          if (event.key === "Enter") {
            event.preventDefault();
            commit();
            (event.target as HTMLInputElement).blur();
          } else if (event.key === "Escape") {
            event.preventDefault();
            setDirty(false);
            setDraft(value);
          }
        }}
        className={`w-full border border-[#E2E8F0] px-3 py-1.5 text-sm font-mono text-black focus:border-black focus:outline-none ${
          highlight ? "bg-amber-50" : "bg-white"
        } ${strong ? "font-bold" : ""}`}
      />
    </label>
  );
}
