"use client";

import React, { useEffect, useState } from "react";
import { Header } from "@/components/landing/Header";
import { HeroSection } from "@/components/landing/HeroSection";
import { InteractiveProductTheater } from "@/components/landing/InteractiveProductTheater";
import { ReceiptMorphVisual } from "@/components/landing/ReceiptMorphVisual";
import { SectionDivider } from "@/components/landing/SectionDivider";
import { SocialProofSection } from "@/components/landing/SocialProofSection";
import { AppSection } from "@/components/landing/AppSection";
import { WorkflowSection } from "@/components/landing/WorkflowSection";
import { FeaturesSection } from "@/components/landing/FeaturesSection";
import { ComparisonTable } from "@/components/landing/ComparisonTable";
import { PricingSection } from "@/components/landing/PricingSection";
import { FAQSection } from "@/components/landing/FAQSection";
import { Footer } from "@/components/landing/Footer";
import { ScrollProgressBar } from "@/components/landing/ScrollProgressBar";

import { LiveTable } from "@/components/dashboard/LiveTable";
import { ExportBar } from "@/components/dashboard/ExportBar";
import { ReceiptDetailModal } from "@/components/dashboard/ReceiptDetailModal";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { generateDeterministicDemoExtraction } from "@/lib/ai/extractor";
import { useI18n } from "@/lib/i18n/context";
import { LaunchSpecialBanner } from "@/components/landing/LaunchSpecialBanner";
import { apiFetch } from "@/lib/csrf/client";

/** Feste Beispiel-Belege für die Vorschau-Tabelle auf der Landingpage — rein statisch, nicht editierbar. */
const DEMO_RECEIPT_FILES = [
  "01_aral_tankbeleg_muenchen.jpg",
  "02_trattoria_bewirtungsbeleg_berlin.jpg",
  "04_rewe_supermarkt_kassenbon.jpg",
];

function buildDemoReceipts(): ProcessedReceipt[] {
  return DEMO_RECEIPT_FILES.map((name, index) => {
    const extractedData = generateDeterministicDemoExtraction(name);
    return {
      ...extractedData,
      id: `demo-${name.split("_")[0]}`,
      imageHash: `hash-${name}`,
      originalFileName: name,
      fileSizeBytes: 184500,
      previewUrl: `/demo/${name}`,
      createdAt: new Date(Date.now() - 3600000 * (index + 1)).toISOString(),
      updatedAt: new Date().toISOString(),
      status: extractedData.validation.needsUserReview ? "needs_review" : "ready",
      isDemo: true,
    };
  });
}

export default function HomePage() {
  const { language } = useI18n();
  const isDe = language === "de";
  const [receipts] = useState<ProcessedReceipt[]>(() => buildDemoReceipts());
  const [launchClaimed, setLaunchClaimed] = useState<number | null>(null);
  const [selectedReceipt, setSelectedReceipt] = useState<ProcessedReceipt | null>(null);

  // Launch-Special Fortschritt für den Banner
  useEffect(() => {
    apiFetch("/api/launch/stats", { cache: "no-store" })
      .then((r) => r.json())
      .then((data) => {
        if (typeof data.claimed === "number") setLaunchClaimed(data.claimed);
      })
      .catch(() => {});
  }, []);

  return (
    <div className="flex min-h-screen flex-col bg-[#F6F9FF] text-[#161C22] font-sans relative overflow-x-hidden">
      {/* Interactive Global Scroll Progress Bar */}
      <ScrollProgressBar />

      {/* Continuous Full-Page Vertical Guide Rails from top to bottom */}
      <div
        className="pointer-events-none absolute inset-y-0 left-1/2 -translate-x-1/2 w-full max-w-[1440px] border-x border-[#E2E8F0] z-20"
        aria-hidden="true"
      />

      {/* Zenith Silver Landing Header */}
      <Header />

      {/* Launch Special Banner (First 500 registrations get 100 free scans) */}
      {launchClaimed !== null && <LaunchSpecialBanner claimed={launchClaimed} />}


      {/* Main Architectural Canvas spanning full screen width with inner framing */}
      <main className="flex-1 w-full relative">

        {/* 01. Hero Section with GSAP reveals and animated scanner showcase */}
        <HeroSection />

        <SectionDivider />
        <AppSection />

        {/* Static Demo Table — view only, no add/edit/delete */}
        <section className="w-full bg-white py-12">
          <div className="max-w-[1440px] mx-auto px-4 sm:px-8">
            <div className="mb-4 flex items-center justify-between">

              <div className="flex items-center gap-2">
                <span className="w-2.5 h-2.5 bg-black"></span>
                <span className="font-mono text-xs uppercase tracking-caps font-semibold text-black">
                  {isDe ? "DEMO BELEGTABELLE" : "DEMO RECEIPT TABLE"}
                </span>
                <span className="font-mono text-[10px] normal-case tracking-normal text-[#94A3B8]">
                  {isDe
                    ? "— Beispiel-Belege zur Vorschau, nur zum Ansehen"
                    : "— sample receipts for preview, view only"}
                </span>
              </div>
            </div>

            {/* Export Action Bar & Totals (read-only: no clear-all) */}
            <ExportBar
              receipts={receipts}
              isPro={false}
              onOpenPaywall={() => {}}
              readOnly
            />

            {/* Static Demo Table */}
            <LiveTable
              receipts={receipts}
              onUpdateReceipt={() => {}}
              onDeleteReceipt={() => {}}
              onViewDetails={(rcpt) => setSelectedReceipt(rcpt)}
              readOnly
            />
          </div>
        </section>


        {/* Social Proof & Performance Metrics with Clean Cards */}
        <SocialProofSection />

        {/* Interactive Product Theater with Real Receipt Photography */}
        <SectionDivider />
        <InteractiveProductTheater />


        {/* Interactive Before / After Morph Slider */}
        <SectionDivider />
        <ReceiptMorphVisual />

        {/* Core Architecture Features Grid */}
        <SectionDivider />
        <FeaturesSection />

        {/* 3-Step Interactive Workflow Walkthrough */}
        <SectionDivider />
        <WorkflowSection />

        {/* Market Comparison Table */}
        <SectionDivider />
        <ComparisonTable />

        {/* Pricing & Licenses Matrix */}
        <SectionDivider />
        <PricingSection />

        {/* Technical FAQ Accordion */}
        <SectionDivider />
        <FAQSection />

      </main>

      {/* Global Architectural Footer */}
      <Footer />

      {/* Receipt Details Modal (view only — no onSave, so edits don't persist) */}
      <ReceiptDetailModal
        receipt={selectedReceipt}
        onClose={() => setSelectedReceipt(null)}
      />
    </div>
  );
}
