"use client";

import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { useI18n } from "@/lib/i18n/context";
import {
  Play,
  Pause,
  RotateCcw,
  Sparkles,
  FileSpreadsheet,
  CheckCircle2,
  Scan,
  Cpu,
  Layers,
  ArrowRight,
  ShieldCheck,
  Zap,
  Download,
  Eye,
  Radio,
  FileText,
  TrendingUp,
  Activity,
  Terminal,
  Calculator,
  Table,
} from "lucide-react";
import gsap from "gsap";

interface TheaterPreset {
  id: string;
  nameDe: string;
  nameEn: string;
  categoryDe: string;
  categoryEn: string;
  imageSrc: string;
  merchant: string;
  date: string;
  gross: number;
  net: number;
  tax19: number;
  tax7: number;
  items: { name: string; qty: number; price: number; tax: number }[];
  boxes: {
    id: string;
    labelDe: string;
    labelEn: string;
    targetCell: string;
    top: string;
    left: string;
    width: string;
    height: string;
    value: string;
    confidence: string;
  }[];
}

const PRESETS: TheaterPreset[] = [
  {
    id: "fuel",
    nameDe: "Aral Tankstelle (Foto)",
    nameEn: "Aral Gas Station (Photo)",
    categoryDe: "KFZ & Treibstoff",
    categoryEn: "Fuel & Vehicle",
    imageSrc: "/demo/fuel_receipt.jpg",
    merchant: "ARAL Station Berlin",
    date: "2024-05-27",
    gross: 75.5,
    net: 63.45,
    tax19: 12.05,
    tax7: 0.0,
    items: [
      { name: "Aral Super E10 (42,68 L @ 1,769€)", qty: 1, price: 75.5, tax: 19 },
    ],
    boxes: [
      { id: "m", labelDe: "HÄNDLER", labelEn: "MERCHANT", targetCell: "C2", top: "24%", left: "30%", width: "40%", height: "9%", value: "ARAL Station Berlin", confidence: "96%" },
      { id: "d", labelDe: "DATUM", labelEn: "DATE", targetCell: "B2", top: "44%", left: "30%", width: "40%", height: "5%", value: "2024-05-27", confidence: "94%" },
      { id: "i", labelDe: "ARTIKEL", labelEn: "ITEM", targetCell: "Sheet 2", top: "48%", left: "30%", width: "40%", height: "6%", value: "Super E10 42,68 Ltr", confidence: "89%" },
      { id: "t", labelDe: "MWST 19%", labelEn: "TAX 19%", targetCell: "E2", top: "54%", left: "30%", width: "40%", height: "8%", value: "12,05 € (19%)", confidence: "95%" },
      { id: "g", labelDe: "BRUTTO", labelEn: "GROSS", targetCell: "F2", top: "61%", left: "30%", width: "40%", height: "6%", value: "75,50 €", confidence: "97%" },
    ],
  },
  {
    id: "groceries",
    nameDe: "REWE Supermarkt (Foto)",
    nameEn: "REWE Supermarket (Photo)",
    categoryDe: "Verpflegung & 7%/19% Split",
    categoryEn: "Groceries & 7%/19% Split",
    imageSrc: "/demo/groceries_receipt.jpg",
    merchant: "REWE Markt GmbH Berlin",
    date: "2023-10-18",
    gross: 15.22,
    net: 13.51,
    tax19: 1.22,
    tax7: 0.49,
    items: [
      { name: "Bio Bananen 1kg", qty: 1, price: 1.99, tax: 7 },
      { name: "JA! Vollmilch 3.5% 2x", qty: 2, price: 1.98, tax: 7 },
      { name: "Dallmayr Prodomo Kaffee", qty: 1, price: 5.49, tax: 7 },
      { name: "Gut & Günstig Eier 10er", qty: 1, price: 1.79, tax: 19 },
      { name: "Coca-Cola PET 2x", qty: 2, price: 2.58, tax: 19 },
      { name: "Pfand PET 2x0.25", qty: 1, price: 0.5, tax: 19 },
    ],
    boxes: [
      { id: "m", labelDe: "HÄNDLER", labelEn: "MERCHANT", targetCell: "C2", top: "18%", left: "32%", width: "36%", height: "12%", value: "REWE Markt Berlin", confidence: "95%" },
      { id: "d", labelDe: "DATUM", labelEn: "DATE", targetCell: "B2", top: "37%", left: "28%", width: "44%", height: "5%", value: "2023-10-18", confidence: "93%" },
      { id: "i", labelDe: "POSITIONEN", labelEn: "ITEMS", targetCell: "Sheet 2", top: "42%", left: "28%", width: "44%", height: "20%", value: "5 Items + Deposit", confidence: "88%" },
      { id: "t", labelDe: "MWST SPLIT", labelEn: "TAX SPLIT", targetCell: "E2 (7% & 19%)", top: "66%", left: "28%", width: "44%", height: "6%", value: "7%: 0,49€ | 19%: 1,22€", confidence: "94%" },
      { id: "g", labelDe: "ZAHLBETRAG", labelEn: "TOTAL", targetCell: "F2", top: "74%", left: "28%", width: "44%", height: "6%", value: "15,22 €", confidence: "97%" },
    ],
  },
  {
    id: "restaurant",
    nameDe: "Trattoria Bewirtung (Foto)",
    nameEn: "Trattoria Restaurant (Photo)",
    categoryDe: "Bewirtung §4 Abs. 5 EStG",
    categoryEn: "Meals & Entertainment",
    imageSrc: "/demo/restaurant_receipt.jpg",
    merchant: "Trattoria Bella Vista München",
    date: "2023-10-12",
    gross: 36.8,
    net: 26.72,
    tax19: 5.08,
    tax7: 0.0,
    items: [
      { name: "2x Pizza Margherita (a 12.50€)", qty: 2, price: 25.0, tax: 19 },
      { name: "1x San Pellegrino 0.75L", qty: 1, price: 6.8, tax: 19 },
      { name: "Trinkgeld (Tip / Bar)", qty: 1, price: 5.0, tax: 0 },
    ],
    boxes: [
      { id: "m", labelDe: "GASTSTÄTTE", labelEn: "RESTAURANT", targetCell: "C2", top: "18%", left: "30%", width: "40%", height: "10%", value: "Trattoria Bella Vista", confidence: "94%" },
      { id: "d", labelDe: "DATUM", labelEn: "DATE", targetCell: "B2", top: "37%", left: "30%", width: "40%", height: "5%", value: "2023-10-12", confidence: "92%" },
      { id: "i", labelDe: "SPEISEN & GETRÄNKE", labelEn: "FOOD & DRINKS", targetCell: "Sheet 2", top: "46%", left: "30%", width: "40%", height: "10%", value: "2x Pizza + Pellegrino", confidence: "87%" },
      { id: "tip", labelDe: "TRINKGELD", labelEn: "TIP", targetCell: "E2 (0% Tax)", top: "64%", left: "30%", width: "40%", height: "5%", value: "5,00 € Tip", confidence: "90%" },
      { id: "g", labelDe: "GESAMTBETRAG", labelEn: "TOTAL AMOUNT", targetCell: "F2", top: "69%", left: "30%", width: "40%", height: "5%", value: "36,80 €", confidence: "96%" },
    ],
  },
];

const STEPS = [
  { id: 1, name: "UPLOAD", titleDe: "Kamera-Erfassung & Kontrast-Filter", titleEn: "Camera Capture & Contrast Filter", icon: Camera },
  { id: 2, name: "OCR SCAN", titleDe: "Multimodaler Vision-Sweep & Tokenizer", titleEn: "Multimodal Vision Sweep & Tokenizer", icon: Scan },
  { id: 3, name: "EXTRACTION", titleDe: "Bounding-Lock & Struktur-Mapping", titleEn: "Bounding Lock & Schema Mapping", icon: Cpu },
  { id: 4, name: "MATH-CHECK", titleDe: "Deterministische Plausibilitäts-Matrix", titleEn: "Deterministic Math Verification Matrix", icon: Calculator },
  { id: 5, name: "EXCEL-EXPORT", titleDe: "Dual-Sheet .XLSX & =SUM() Formeln", titleEn: "Dual-Sheet .XLSX & =SUM() Formulas", icon: Table },
];

function Camera(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/>
      <circle cx="12" cy="13" r="3"/>
    </svg>
  );
}

export function InteractiveProductTheater() {
  const { language } = useI18n();
  const isDe = language === "de";

  const [activePreset, setActivePreset] = useState<TheaterPreset>(PRESETS[0]);
  const [activeStep, setActiveStep] = useState<number>(1);
  const [isPlaying, setIsPlaying] = useState<boolean>(true);
  const [activeExcelTab, setActiveExcelTab] = useState<"summary" | "items">("summary");
  const [cameraFlash, setCameraFlash] = useState<boolean>(false);
  const [hoveredBox, setHoveredBox] = useState<string | null>(null);

  const laserRef = useRef<HTMLDivElement>(null);
  const theaterRef = useRef<HTMLDivElement>(null);

  // Automated step progression when playing
  useEffect(() => {
    if (!isPlaying) return;

    const timer = setInterval(() => {
      setActiveStep((prev) => (prev >= 5 ? 1 : prev + 1));
    }, 2800);

    return () => clearInterval(timer);
  }, [isPlaying]);

  // Trigger camera flash on step 1
  useEffect(() => {
    if (activeStep === 1) {
      setCameraFlash(true);
      const flashTimer = setTimeout(() => setCameraFlash(false), 250);
      return () => clearTimeout(flashTimer);
    }
  }, [activeStep]);

  // GSAP Laser animation on step 2
  useEffect(() => {
    if (laserRef.current && activeStep === 2) {
      gsap.fromTo(
        laserRef.current,
        { top: "0%", opacity: 1 },
        { top: "100%", opacity: 0.9, duration: 1.8, ease: "power2.inOut" }
      );
    }
  }, [activeStep]);

  return (
    <section
      ref={theaterRef}
      className="w-full bg-[#F6F9FF] font-sans py-20 relative"
    >
      <div className="max-w-[1440px] mx-auto px-4 sm:px-8 border-x border-[#E2E8F0] relative">
        {/* Section Header */}
        <div className="flex flex-col md:flex-row md:items-end justify-between mb-10 gap-6">
          <div>
            <div className="flex items-center gap-2 mb-3">
              <span className="w-2.5 h-2.5 bg-black animate-pulse"></span>
              <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
                LIVE SIMULATION & DEMO
              </span>
            </div>
          <h2 className="font-display text-3xl sm:text-4xl md:text-5xl font-bold tracking-tight text-black max-w-2xl leading-[1.08]">
            {isDe
              ? "Erlebe die Verwandlung: Foto zu Dual-Sheet Excel in 5 Schritten."
              : "Witness the transformation: Photo to Dual-Sheet Excel in 5 steps."}
          </h2>
        </div>
        <p className="font-sans text-sm text-[#475569] max-w-md leading-relaxed">
          {isDe
            ? "Jeder Schritt visualisiert exakt, was im Hintergrund passiert: Vom Kamera-Scan über die neuronale Erkennung bis zum mathematischen Beweis und der fertigen .xlsx-Datei."
            : "Every step reveals what happens under the hood: From camera capture and neural recognition to mathematical proof and formatted .xlsx compilation."}
        </p>
      </div>

      {/* Preset Selector */}
      <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
        <div className="flex flex-wrap items-center gap-2 sm:gap-3">
          <span className="font-mono text-xs text-[#64748B] uppercase tracking-caps mr-1 hidden sm:inline">
            {isDe ? "BELEG-FOTO WÄHLEN:" : "SELECT SAMPLE RECEIPT:"}
          </span>
          {PRESETS.map((preset) => (
            <button
              key={preset.id}
              onClick={() => {
                setActivePreset(preset);
                setActiveStep(1);
              }}
              className={`px-4 py-2 font-mono text-xs uppercase tracking-caps transition-all flex items-center gap-2 border ${
                activePreset.id === preset.id
                  ? "bg-black text-white border-black font-semibold shadow-sm"
                  : "bg-white text-[#475569] border-[#E2E8F0] hover:border-black hover:text-black"
              }`}
            >
              <Scan className="w-3.5 h-3.5" />
              <span>{isDe ? preset.nameDe : preset.nameEn}</span>
              <span className="text-[10px] opacity-75">({preset.gross.toFixed(2)} €)</span>
            </button>
          ))}
        </div>

        {/* Live Cinema Badge */}
        <div className="flex items-center gap-2 font-mono text-xs text-[#475569]">
          <Radio className="w-3.5 h-3.5 text-black animate-pulse" />
          <span className="uppercase tracking-wider font-semibold">
            {isDe
              ? isPlaying
                ? "AUTO-CINEMA MODUS LÄUFT"
                : "INTERAKTIVER SCHRITT-MODUS"
              : isPlaying
              ? "AUTO-PLAY RUNNING"
              : "INTERACTIVE STEP MODE"}
          </span>
        </div>
      </div>

      {/* Main Theater Box Styled in Pure Zenith Silver */}
      <div className="bg-white text-black border-2 border-black overflow-hidden flex flex-col justify-between shadow-xl">
        {/* Top Video HUD Controller in Zenith Silver */}
        <div className="bg-[#F8FAFC] px-4 sm:px-6 py-3 border-b border-[#E2E8F0] flex flex-wrap items-center justify-between gap-4 font-mono text-xs">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setIsPlaying(!isPlaying)}
              className="px-3.5 py-1.5 bg-black text-white hover:bg-[#334155] transition-colors flex items-center gap-1.5 font-bold uppercase tracking-caps"
            >
              {isPlaying ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}
              <span>{isPlaying ? "Pause" : "Play"}</span>
            </button>

            <button
              onClick={() => setActiveStep(1)}
              className="p-1.5 bg-white border border-[#E2E8F0] text-black hover:border-black transition-colors"
              title={isDe ? "Von vorne starten" : "Start from beginning"}
            >
              <RotateCcw className="w-3.5 h-3.5" />
            </button>

            <div className="hidden sm:flex items-center gap-2 pl-2 border-l border-[#E2E8F0]">
              <span className="text-black font-bold">{isDe ? "SCHRITT" : "STEP"} {activeStep}:</span>
              <span className="text-[#475569] uppercase tracking-wider font-semibold">
                {isDe ? STEPS[activeStep - 1].titleDe : STEPS[activeStep - 1].titleEn}
              </span>
            </div>
          </div>


          <div className="flex items-center gap-4 text-[11px] text-[#64748B]">
            <span className="flex items-center gap-1.5 text-black font-semibold">
              <span className="w-2 h-2 rounded-full bg-black animate-ping"></span>
              <span>{isDe ? "KI-VISION // OCR KERNEL" : "AI VISION // OCR KERNEL"}</span>
            </span>
            <span className="hidden md:inline">60 FPS REALTIME</span>
          </div>
        </div>

        {/* 5-Step Timeline Navigation in Zenith Silver */}
        <div className="grid grid-cols-5 bg-white border-b border-[#E2E8F0]">
          {STEPS.map((s) => {
            const Icon = s.icon;
            return (
              <button
                key={s.id}
                onClick={() => {
                  setActiveStep(s.id);
                  setIsPlaying(false);
                }}
                className={`p-2.5 sm:p-3 text-left font-mono transition-all border-r border-[#E2E8F0] last:border-r-0 ${
                  activeStep === s.id
                    ? "bg-black text-white font-bold"
                    : activeStep > s.id
                    ? "bg-[#EEF4FC] text-black font-semibold"
                    : "text-[#64748B] hover:text-black hover:bg-[#F8FAFC]"
                }`}
              >
                <div className="flex items-center gap-1.5 mb-0.5">
                  <Icon className="w-3 h-3 shrink-0" />
                  <span className="text-[10px] sm:text-xs uppercase tracking-caps truncate">
                    {s.name}
                  </span>
                </div>
                <div className="text-[9px] opacity-70 hidden md:block truncate">
                  {(isDe ? s.titleDe : s.titleEn).split(" ")[0]} {(isDe ? s.titleDe : s.titleEn).split(" ")[1]}
                </div>
              </button>
            );
          })}
        </div>

        {/* Dynamic Split Screen in Clean Zenith Silver */}
        <div className="grid grid-cols-1 lg:grid-cols-12 min-h-[540px] bg-white">
          {/* Left Column: Photo Viewfinder / Laser / Bounding Boxes (5 cols) */}
          <div className="lg:col-span-5 p-6 sm:p-8 flex flex-col items-center justify-center relative border-b lg:border-b-0 lg:border-r border-[#E2E8F0] bg-[#F8FAFC] overflow-hidden select-none">
            {cameraFlash && (
              <div className="absolute inset-0 bg-white z-50 pointer-events-none transition-opacity duration-200">
              </div>
            )}

            {/* Viewfinder Reticles */}
            <div className="absolute top-4 left-4 w-4 h-4 border-t-2 border-l-2 border-black"></div>
            <div className="absolute top-4 right-4 w-4 h-4 border-t-2 border-r-2 border-black"></div>
            <div className="absolute bottom-4 left-4 w-4 h-4 border-b-2 border-l-2 border-black"></div>
            <div className="absolute bottom-4 right-4 w-4 h-4 border-b-2 border-r-2 border-black"></div>

            {/* Viewfinder Telemetry */}
            <div className="absolute top-6 left-8 right-8 flex justify-between font-mono text-[10px] text-[#475569] pointer-events-none z-20 font-bold">
              <span>LIVE FEED // 4K 60FPS</span>
              <span>{activePreset.id.toUpperCase()}_SCAN.RAW</span>
            </div>

            {/* High-Res Photo Container */}
            <div className="relative w-full max-w-[310px] aspect-[3/4] overflow-hidden border-2 border-black shadow-xl bg-white my-4">
              <Image
                src={activePreset.imageSrc}
                alt={isDe ? activePreset.nameDe : activePreset.nameEn}
                fill
                priority
                className={`object-cover transition-transform duration-700 ${
                  activeStep >= 2 ? "scale-[1.02]" : "scale-100"
                }`}
              />

              {/* Step 2: Animated Scanning Laser Sweep */}
              {activeStep === 2 && (
                <div
                  ref={laserRef}
                  className="absolute left-0 right-0 h-1 bg-black z-30 pointer-events-none shadow-[0_0_12px_rgba(0,0,0,0.8)]"
                />
              )}

              {/* Step 3 & 4: Sharp Bounding Boxes */}
              {activeStep >= 3 &&
                activePreset.boxes.map((box) => (
                  <div
                    key={box.id}
                    onMouseEnter={() => setHoveredBox(box.id)}
                    onMouseLeave={() => setHoveredBox(null)}
                    className={`absolute border-2 transition-all duration-300 z-20 cursor-pointer ${
                      hoveredBox === box.id
                        ? "border-black bg-black/20 scale-105 shadow-md"
                        : "border-black bg-black/10 shadow-sm"
                    }`}
                    style={{
                      top: box.top,
                      left: box.left,
                      width: box.width,
                      height: box.height,
                    }}
                  >
                    <span className="absolute -top-3.5 left-0 bg-black text-white font-mono text-[7.5px] px-1 py-0.2 border border-black whitespace-nowrap font-bold">
                      {isDe ? box.labelDe : box.labelEn}: {box.value}
                    </span>
                  </div>
                ))}
            </div>

            {/* Bottom Photo Status */}
            <div className="font-mono text-[11px] text-[#475569] flex items-center justify-between w-full max-w-[310px]">
              <span className="flex items-center gap-1 text-black font-semibold">
                <CheckCircle2 className="w-3.5 h-3.5" />
                <span>{isDe ? "Sharp: Kontrast optimiert" : "Sharp: Contrast optimized"}</span>
              </span>
              <span>ISO-8601 Valid</span>
            </div>
          </div>

          {/* Right Column: 5-phase stages */}
          <div className="lg:col-span-7 p-6 sm:p-8 bg-white flex flex-col justify-between relative overflow-hidden">
            {/* --------------------------------------------------------------- */}
            {/* STAGE 1: upload HUD */}
            {/* --------------------------------------------------------------- */}
            {activeStep === 1 && (
              <div className="space-y-6 animate-fade-in my-auto">
                <div className="flex items-center justify-between border-b border-[#E2E8F0] pb-3">
                  <span className="font-mono text-xs text-black uppercase tracking-caps font-bold">
                    {isDe ? "Beleg-Ingestion & Vorfilterung" : "Receipt Ingestion & Pre-Filtering"}
                  </span>
                  <span className="font-mono text-[10px] bg-[#EEF4FC] border border-[#E2E8F0] px-2 py-0.5 text-black font-bold">
                    {isDe ? "4K HOCHAUFLÖSEND" : "4K HIGH-RES"}
                  </span>
                </div>

                <div className="p-6 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-xs space-y-4">
                  <div className="text-black font-bold text-sm">
                    {isDe ? "📸 Bildempfang & Kontrast-Vorfilterung" : "📸 Image Ingestion & Contrast Pre-Filtering"}
                  </div>
                  <p className="text-[#475569] font-sans text-xs leading-relaxed">
                    {isDe
                      ? "Der Kassenbon wurde erfolgreich hochgeladen. Das integrierte Sharp-Bildmodul richtet die Ausrichtung automatisch aus, entfernt chromatische Aberrationen und verstärkt verblasste Thermopapier-Tinte für die KI."
                      : "Receipt uploaded successfully. The integrated image module auto-aligns rotation, removes aberrations, and enhances faded thermal paper ink for the AI pipeline."}
                  </p>
                  <div className="grid grid-cols-2 gap-3 pt-2">
                    <div className="p-3 bg-white border border-[#E2E8F0]">
                      <div className="text-[#64748B] text-[10px]">{isDe ? "DATEIFORMAT" : "FILE FORMAT"}</div>
                      <div className="text-black font-bold">JPEG (2.4 MB RAW)</div>
                    </div>
                    <div className="p-3 bg-white border border-[#E2E8F0]">
                      <div className="text-[#64748B] text-[10px]">{isDe ? "KONTRAST-OPTIMIERUNG" : "CONTRAST ENGINE"}</div>
                      <div className="text-black font-bold">+45% (Sharp Kernel)</div>
                    </div>
                  </div>
                </div>

                <div className="flex items-center justify-between font-mono text-xs text-[#64748B] pt-2">
                  <span>{isDe ? "Warte auf OCR-Laser-Trigger..." : "Awaiting OCR laser sweep..."}</span>
                  <span className="text-black font-bold">{isDe ? "Bereit für neuronales Parsing →" : "Ready for neural parsing →"}</span>
                </div>
              </div>
            )}

            {/* --------------------------------------------------------------- */}
            {/* STAGE 2: LIVE OCR STREAMING WITH ACTIVE TERMINAL */}
            {/* --------------------------------------------------------------- */}
            {activeStep === 2 && (
              <div className="space-y-4 animate-fade-in my-auto">
                <div className="flex items-center justify-between border-b border-[#E2E8F0] pb-3">
                  <span className="font-mono text-xs text-black uppercase tracking-caps font-bold flex items-center gap-2">
                    <Scan className="w-4 h-4" />
                    <span>{isDe ? "Vision AI Tokenizer Stream" : "Vision AI Tokenizer Stream"}</span>
                  </span>
                  <span className="font-mono text-[10px] bg-black text-white px-2 py-0.5 font-bold">
                    DEEPSEEK-OCR // ACTIVE
                  </span>
                </div>

                {/* Simulated Realtime OCR Terminal Feed */}
                <div className="p-4 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-xs text-black space-y-2 h-[220px] overflow-y-auto">
                  <div className="text-[#64748B] text-[11px] pb-1 border-b border-[#E2E8F0]">
                    [LOG] Token-Stream initialisiert // Model: openai/gpt-5.6-luna
                  </div>
                  <div className="space-y-1 text-[11px]">
                    <p className="text-[#334155]">&gt; DETECT_BOUNDING_BOX(merchant) =&gt; &quot;{activePreset.merchant}&quot; [96%]</p>
                    <p className="text-[#334155]">&gt; DETECT_DATE(iso_standard) =&gt; &quot;{activePreset.date}&quot; [94%]</p>
                    <p className="text-[#334155]">&gt; DETECT_LINE_ITEMS(itemized_list) =&gt; {activePreset.items.length} {isDe ? "Positionen erkannt" : "positions found"} [91%]</p>
                    <p className="text-[#334155]">&gt; DETECT_TAX_SPLIT(7%, 19%) =&gt; 19%: {activePreset.tax19.toFixed(2)}€ [95%]</p>
                    <p className="text-black font-bold">&gt; DETECT_GROSS_TOTAL(totalAmount) =&gt; {activePreset.gross.toFixed(2)}€ [97%]</p>
                    <p className="text-black font-bold pt-1">&gt;&gt; OCR_TOKEN_EXTRACTION_SUCCESS: 100% Valid</p>
                  </div>
                </div>

                <div className="p-3 bg-[#EEF4FC] border border-[#E2E8F0] font-mono text-xs flex justify-between items-center">
                  <span className="text-[#475569]">{isDe ? "Status:" : "Status:"} <strong className="text-black">1.482 Tokens extrahiert</strong></span>
                  <span className="text-black font-bold">{isDe ? "Schema-Mapping wird gestartet →" : "Initiating schema mapping →"}</span>
                </div>
              </div>
            )}

            {/* --------------------------------------------------------------- */}
            {/* STAGE 3: STRUCTURED DATA CHIP EXTRACTION */}
            {/* --------------------------------------------------------------- */}
            {activeStep === 3 && (
              <div className="space-y-6 animate-fade-in my-auto">
                <div className="flex items-center justify-between border-b border-[#E2E8F0] pb-3">
                  <span className="font-mono text-xs text-black uppercase tracking-caps font-bold flex items-center gap-2">
                    <Cpu className="w-4 h-4" />
                    <span>{isDe ? "Struktur-Extraktion & Bounding-Locks" : "Structural Extraction & Bounding Locks"}</span>
                  </span>
                  <span className="font-mono text-[10px] bg-black text-white px-2 py-0.5 font-bold">
                    {isDe ? "ZOD-SCHEMA VALIDIERUNG" : "ZOD SCHEMA VALIDATION"}
                  </span>
                </div>

                <div className="grid grid-cols-2 gap-3 font-mono text-xs">
                  <div className="p-3.5 bg-[#F8FAFC] border border-[#E2E8F0] space-y-1">
                    <div className="text-[10px] text-[#64748B]">{isDe ? "HÄNDLER / AUSSTELLER" : "MERCHANT / VENDOR"}</div>
                    <div className="text-black font-bold text-sm truncate">{activePreset.merchant}</div>
                    <div className="text-emerald-700 text-[10px] font-bold">Confidence: 96%</div>
                  </div>

                  <div className="p-3.5 bg-[#F8FAFC] border border-[#E2E8F0] space-y-1">
                    <div className="text-[10px] text-[#64748B]">{isDe ? "BELEGDATUM (ISO-8601)" : "RECEIPT DATE (ISO-8601)"}</div>
                    <div className="text-black font-bold text-sm">{activePreset.date}</div>
                    <div className="text-emerald-700 text-[10px] font-bold">Confidence: 94%</div>
                  </div>

                  <div className="p-3.5 bg-[#F8FAFC] border border-[#E2E8F0] space-y-1">
                    <div className="text-[10px] text-[#64748B]">{isDe ? "NETTO-BETRAG" : "NET AMOUNT"}</div>
                    <div className="text-black font-bold text-sm">{activePreset.net.toFixed(2)} €</div>
                    <div className="text-[#64748B] text-[10px]">{isDe ? "Mapping: Spalte D" : "Mapping: Column D"}</div>
                  </div>

                  <div className="p-3.5 bg-[#F8FAFC] border border-[#E2E8F0] space-y-1">
                    <div className="text-[10px] text-[#64748B]">{isDe ? "MWST (19% / 7%)" : "TAX (19% / 7%)"}</div>
                    <div className="text-black font-bold text-sm">
                      {activePreset.tax19.toFixed(2)} € / {activePreset.tax7.toFixed(2)} €
                    </div>
                    <div className="text-[#64748B] text-[10px]">{isDe ? "Mapping: Spalte E" : "Mapping: Column E"}</div>
                  </div>
                </div>

                <div className="p-3 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-xs flex justify-between items-center text-[#475569]">
                  <span>{isDe ? "Kategorie-Zuordnung:" : "Category Assignment:"} <strong className="text-black">{isDe ? activePreset.categoryDe : activePreset.categoryEn}</strong></span>
                  <span className="text-black font-bold">{isDe ? "5 Felder gebunden →" : "5 fields mapped →"}</span>
                </div>
              </div>
            )}

            {/* --------------------------------------------------------------- */}
            {/* STAGE 4: deterministic math matrix */}
            {/* --------------------------------------------------------------- */}
            {activeStep === 4 && (
              <div className="space-y-6 animate-fade-in my-auto">
                <div className="flex items-center justify-between border-b border-[#E2E8F0] pb-3">
                  <span className="font-mono text-xs text-black uppercase tracking-caps font-bold flex items-center gap-2">
                    <Calculator className="w-4 h-4" />
                    <span>{isDe ? "Deterministischer Math-Proof" : "Deterministic Math Proof"}</span>
                  </span>
                  <span className="font-mono text-[10px] bg-black text-white px-2 py-0.5 font-bold">
                    {isDe ? "✓ SUMME GEPRÜFT" : "✓ TOTAL VERIFIED"}
                  </span>
                </div>

                {/* Big Visual Math Ledger Equation */}
                <div className="p-6 bg-[#F8FAFC] border-2 border-black font-mono text-center space-y-4 shadow-sm">
                  <div className="text-[11px] text-black uppercase tracking-widest font-bold">
                    {isDe ? "DETERMINISTISCHER ABGLEICH (NETTO + MWST = BRUTTO)" : "DETERMINISTIC RECONCILIATION (NET + TAX = GROSS)"}
                  </div>

                  <div className="grid grid-cols-3 gap-3 items-center py-2">
                    <div className="p-3 bg-white border border-[#E2E8F0]">
                      <div className="text-[10px] text-[#64748B]">{isDe ? "NETTO" : "NET"}</div>
                      <div className="text-base sm:text-lg font-bold text-black">
                        {activePreset.net.toFixed(2)} €
                      </div>
                    </div>

                    <div className="p-3 bg-white border border-[#E2E8F0]">
                      <div className="text-[10px] text-[#64748B]">{isDe ? "MWST (19%)" : "TAX (19%)"}</div>
                      <div className="text-base sm:text-lg font-bold text-black">
                        {activePreset.tax19.toFixed(2)} €
                      </div>
                    </div>

                    <div className="p-3 bg-[#EEF4FC] border border-black">
                      <div className="text-[10px] text-black font-bold">{isDe ? "BRUTTO GEPRÜFT" : "GROSS VERIFIED"}</div>
                      <div className="text-base sm:text-lg font-extrabold text-black">
                        {activePreset.gross.toFixed(2)} €
                      </div>
                    </div>
                  </div>

                  <div className="text-xs text-black font-mono pt-1 font-bold">
                    {activePreset.net.toFixed(2)} € + {activePreset.tax19.toFixed(2)} € = {activePreset.gross.toFixed(2)} € {isDe ? "(Rundungstoleranz: ±0,02 €)" : "(Rounding tolerance: ±0.02 €)"}
                  </div>
                </div>

                <div className="p-3 bg-white border border-[#E2E8F0] font-mono text-xs flex justify-between items-center text-[#64748B]">
                  <span>{isDe ? "Kategorie:" : "Category:"} <strong className="text-black">{isDe ? activePreset.categoryDe : activePreset.categoryEn}</strong></span>
                  <span className="text-black font-bold">{isDe ? "Bereit für Excel-Kompilierung →" : "Ready for Excel compilation →"}</span>
                </div>
              </div>
            )}

            {/* --------------------------------------------------------------- */}
            {/* STAGE 5: dual-sheet Excel compilation */}
            {/* --------------------------------------------------------------- */}
            {activeStep === 5 && (
              <div className="space-y-4 animate-fade-in my-auto">
                {/* Excel Application Titlebar */}
                <div className="flex items-center justify-between pb-3 border-b border-[#E2E8F0]">
                  <div className="flex items-center gap-2 font-mono text-xs">
                    <FileSpreadsheet className="w-4 h-4 text-black" />
                    <span className="font-bold text-black uppercase tracking-wider">
                      Dual-Sheet Excel Engine (.xlsx)
                    </span>
                  </div>
                  <span className="font-mono text-[10px] bg-black text-white px-2 py-0.5 font-bold">
                    {isDe ? "✓ FERTIG KOMPILIERT" : "✓ COMPILED"}
                  </span>
                </div>

                {/* Sheet Tabs */}
                <div className="flex items-center gap-1 border-b border-[#E2E8F0]">
                  <button
                    onClick={() => setActiveExcelTab("summary")}
                    className={`px-3 py-1.5 font-mono text-[11px] uppercase tracking-caps transition-colors flex items-center gap-1.5 border-b-2 ${
                      activeExcelTab === "summary"
                        ? "border-black text-black font-bold bg-[#EEF4FC]"
                        : "border-transparent text-[#64748B] hover:text-black"
                    }`}
                  >
                    <Layers className="w-3 h-3 text-black" />
                    <span>{isDe ? "Sheet 1: Zusammenfassung" : "Sheet 1: Summary"}</span>
                  </button>
                  <button
                    onClick={() => setActiveExcelTab("items")}
                    className={`px-3 py-1.5 font-mono text-[11px] uppercase tracking-caps transition-colors flex items-center gap-1.5 border-b-2 ${
                      activeExcelTab === "items"
                        ? "border-black text-black font-bold bg-[#EEF4FC]"
                        : "border-transparent text-[#64748B] hover:text-black"
                    }`}
                  >
                    <Layers className="w-3 h-3 text-black" />
                    <span>{isDe ? "Sheet 2: Einzelpositionen" : "Sheet 2: Line Items"}</span>
                  </button>
                </div>

                {/* Formula Bar */}
                <div className="flex items-center gap-2 px-3 py-1.5 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-xs text-[#64748B]">
                  <span className="text-black font-bold">fx</span>
                  <span className="text-black font-bold">
                    =SUM(F2:F3)
                  </span>
                </div>

                {/* Live Excel Table Grid */}
                <div className="border border-[#E2E8F0] overflow-x-auto bg-white shadow-sm">
                  {activeExcelTab === "summary" ? (
                    <table className="w-full text-left font-mono text-xs border-collapse">
                      <thead>
                        <tr className="bg-black text-white text-[10px] uppercase tracking-wider">
                          <th className="p-2 border-r border-white/20">A: ID</th>
                          <th className="p-2 border-r border-white/20">B: {isDe ? "DATUM" : "DATE"}</th>
                          <th className="p-2 border-r border-white/20">C: {isDe ? "HÄNDLER" : "MERCHANT"}</th>
                          <th className="p-2 border-r border-white/20 text-right">D: {isDe ? "NETTO" : "NET"}</th>
                          <th className="p-2 border-r border-white/20 text-right">E: {isDe ? "MWST" : "TAX"}</th>
                          <th className="p-2 text-right">F: {isDe ? "BRUTTO" : "GROSS"}</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-[#E2E8F0] text-black">
                        <tr className="bg-[#EEF4FC] font-bold">
                          <td className="p-2 border-r border-[#E2E8F0] text-[#64748B]">REC-001</td>
                          <td className="p-2 border-r border-[#E2E8F0]">{activePreset.date}</td>
                          <td className="p-2 border-r border-[#E2E8F0] text-black">{activePreset.merchant}</td>
                          <td className="p-2 border-r border-[#E2E8F0] text-right">{activePreset.net.toFixed(2)} €</td>
                          <td className="p-2 border-r border-[#E2E8F0] text-right">{(activePreset.tax19 + activePreset.tax7).toFixed(2)} €</td>
                          <td className="p-2 text-right font-extrabold text-black">{activePreset.gross.toFixed(2)} €</td>
                        </tr>

                        <tr className="hover:bg-[#F8FAFC] opacity-60">
                          <td className="p-2 border-r border-[#E2E8F0] text-[#64748B]">REC-002</td>
                          <td className="p-2 border-r border-[#E2E8F0]">2026-08-14</td>
                          <td className="p-2 border-r border-[#E2E8F0]">Deutsche Bahn ICE</td>
                          <td className="p-2 border-r border-[#E2E8F0] text-right">82,24 €</td>
                          <td className="p-2 border-r border-[#E2E8F0] text-right">5,76 € (7%)</td>
                          <td className="p-2 text-right">88,00 €</td>
                        </tr>

                        <tr className="bg-black text-white font-bold border-t-2 border-black">
                          <td colSpan={3} className="p-2 border-r border-white/20 uppercase tracking-caps text-white">
                            {isDe ? "SUMMENZEILE (=SUM)" : "SUMMARY ROW (=SUM)"}
                          </td>
                          <td className="p-2 border-r border-white/20 text-right">
                            {(activePreset.net + 82.24).toFixed(2)} €
                          </td>
                          <td className="p-2 border-r border-white/20 text-right">
                            {(activePreset.tax19 + activePreset.tax7 + 5.76).toFixed(2)} €
                          </td>
                          <td className="p-2 text-right text-white font-extrabold">
                            {(activePreset.gross + 88.0).toFixed(2)} €
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  ) : (
                    <table className="w-full text-left font-mono text-xs border-collapse">
                      <thead>
                        <tr className="bg-black text-white text-[10px] uppercase tracking-wider">
                          <th className="p-2 border-r border-white/20">{isDe ? "BELEG" : "RECEIPT"}</th>
                          <th className="p-2 border-r border-white/20">{isDe ? "ARTIKEL" : "ITEM"}</th>
                          <th className="p-2 border-r border-white/20 text-center">{isDe ? "MENGE" : "QTY"}</th>
                          <th className="p-2 border-r border-white/20 text-center">{isDe ? "MWST %" : "TAX %"}</th>
                          <th className="p-2 text-right">{isDe ? "BETRAG" : "AMOUNT"}</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-[#E2E8F0] text-black">
                        {activePreset.items.map((item, idx) => (
                          <tr key={idx} className="hover:bg-[#F8FAFC]">
                            <td className="p-2 border-r border-[#E2E8F0] text-[#64748B]">
                              {(isDe ? activePreset.nameDe : activePreset.nameEn).split(" ")[0]}
                            </td>
                            <td className="p-2 border-r border-[#E2E8F0] text-black">
                              {item.name}
                            </td>
                            <td className="p-2 border-r border-[#E2E8F0] text-center">{item.qty}</td>
                            <td className="p-2 border-r border-[#E2E8F0] text-center">{item.tax}%</td>
                            <td className="p-2 text-right font-bold text-black">
                              {item.price.toFixed(2)} €
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            )}

            {/* Bottom Actions Bar */}
            <div className="mt-6 pt-4 border-t border-[#E2E8F0] flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div className="font-mono text-xs text-[#64748B] flex items-center gap-2">
                <ShieldCheck className="w-4 h-4 text-black" />
                <span>{isDe ? "Dual-Sheet .xlsx · CSV (UTF-8)" : "Dual-Sheet .xlsx · CSV (UTF-8)"}</span>
              </div>

              <a
                href="/dashboard"
                className="px-5 py-2.5 bg-black text-white font-mono text-xs uppercase tracking-caps font-bold hover:bg-[#334155] transition-colors flex items-center justify-center gap-2"
              >
                <span>{isDe ? "Live im Dashboard öffnen" : "Open in Live Dashboard"}</span>
                <ArrowRight className="w-4 h-4" />
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
);
}
