"use client";

import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import { useState, useEffect } from "react";
import NavbarStyleApple from "@/components/navbar/NavbarStyleApple/NavbarStyleApple";
import HeroCentered from "@/components/sections/hero/HeroCentered";
import MetricSplitMediaAbout from "@/components/sections/about/MetricSplitMediaAbout";
import FeatureCardSixteen from "@/components/sections/feature/FeatureCardSixteen";
import MetricCardSeven from "@/components/sections/metrics/MetricCardSeven";
import TestimonialCardThirteen from "@/components/sections/testimonial/TestimonialCardThirteen";
import FaqBase from "@/components/sections/faq/FaqBase";
import ContactSplit from "@/components/sections/contact/ContactSplit";
import FooterLogoEmphasis from "@/components/sections/footer/FooterLogoEmphasis";
import TimelineProcessFlow from "@/components/cardStack/layouts/timelines/TimelineProcessFlow";
import { Moon, Sun } from "lucide-react";
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";

gsap.registerPlugin(ScrollTrigger);

const lightTheme = {
  "--background": "#ffffff",  "--card": "#f9f9f9",  "--foreground": "#000000",  "--primary-cta": "#000000",  "--secondary-cta": "#f9f9f9",  "--accent": "#e2e2e2",  "--background-accent": "#c4c4c4",  "--primary-cta-text": "#ffffff",  "--secondary-cta-text": "#000000"
};

const darkTheme = {
  "--background": "#0a0a0a",  "--card": "#1a1a1a",  "--foreground": "#ffffff",  "--primary-cta": "#ffffff",  "--secondary-cta": "#1a1a1a",  "--accent": "#737373",  "--background-accent": "#737373",  "--primary-cta-text": "#0a0a0a",  "--secondary-cta-text": "#ffffff"
};

export default function LandingPage() {
  const [isDarkMode, setIsDarkMode] = useState(false);

  const theme = isDarkMode ? darkTheme : lightTheme;

  const toggleTheme = () => {
    setIsDarkMode(!isDarkMode);
    Object.entries(theme).forEach(([key, value]) => {
      document.documentElement.style.setProperty(key, value);
    });
  };

  useEffect(() => {
    // Initialize GSAP animations
    gsap.utils.toArray<HTMLElement>("[data-section]").forEach((section) => {
      // Fade in on scroll
      gsap.from(section, {
        opacity: 0,
        duration: 0.8,
        scrollTrigger: {
          trigger: section,
          start: "top 80%",          end: "top 20%",          scrub: 1,
          markers: false
        }
      });

      // Parallax effect on hero
      if (section.id === "hero") {
        gsap.to(section, {
          y: 50,
          duration: 0.5,
          scrollTrigger: {
            trigger: section,
            start: "top center",            end: "bottom center",            scrub: 0.5,
            markers: false
          }
        });
      }
    });

    // Animate hero title and description with stagger
    gsap.from("#hero h1, #hero p", {
      opacity: 0,
      y: 30,
      duration: 0.8,
      stagger: 0.2,
      delay: 0.3
    });

    // Button hover effects
    const buttons = document.querySelectorAll("button[class*='button']");
    buttons.forEach((button) => {
      button.addEventListener("mouseenter", () => {
        gsap.to(button, {
          scale: 1.05,
          duration: 0.3,
          overwrite: "auto"
        });
      });
      button.addEventListener("mouseleave", () => {
        gsap.to(button, {
          scale: 1,
          duration: 0.3,
          overwrite: "auto"
        });
      });
    });

    // Animate metric cards with scroll trigger
    gsap.from("[class*='metric']", {
      opacity: 0,
      scale: 0.8,
      duration: 0.6,
      stagger: 0.1,
      scrollTrigger: {
        trigger: "#metrics",        start: "top 80%",        end: "top 20%",        scrub: 1,
        markers: false
      }
    });

    // Animate testimonial cards
    gsap.from("[class*='testimonial']", {
      opacity: 0,
      x: -30,
      duration: 0.6,
      stagger: 0.15,
      scrollTrigger: {
        trigger: "#testimonials",        start: "top 80%",        end: "top 20%",        scrub: 0.5,
        markers: false
      }
    });

    // Text reveal effect on section titles
    gsap.utils.toArray<HTMLElement>("[data-section] h2, [data-section] h3").forEach((heading) => {
      gsap.from(heading, {
        opacity: 0,
        y: 20,
        duration: 0.6,
        scrollTrigger: {
          trigger: heading,
          start: "top 90%",          end: "top 70%",          scrub: 0.3,
          markers: false
        }
      });
    });

    // Cleanup
    return () => {
      ScrollTrigger.getAll().forEach((trigger) => trigger.kill());
    };
  }, []);

  return (
    <ThemeProvider
      defaultButtonVariant="text-stagger"
      defaultTextAnimation="background-highlight"
      borderRadius="pill"
      contentWidth="compact"
      sizing="mediumLargeSizeLargeTitles"
      background="circleGradient"
      cardStyle="soft-shadow"
      primaryButtonStyle="radial-glow"
      secondaryButtonStyle="layered"
      headingFontWeight="medium"
    >
      <div id="nav" data-section="nav">
        <div className="flex items-center justify-between p-4">
          <NavbarStyleApple
            brandName="Aether DB"
            navItems={[
              { name: "What is Aether DB", id: "what-is" },
              { name: "How It Works", id: "process" },
              { name: "Features", id: "features" },
              { name: "FAQ", id: "faq" },
              { name: "Contact", id: "contact" }
            ]}
          />
          <button
            onClick={toggleTheme}
            className="ml-4 p-2 rounded-lg hover:bg-accent transition-colors"
            aria-label="Toggle theme"
          >
            {isDarkMode ? (
              <Sun className="w-6 h-6" />
            ) : (
              <Moon className="w-6 h-6" />
            )}
          </button>
        </div>
      </div>

      <div id="hero" data-section="hero">
        <HeroCentered
          title="Stop Writing SQL. Start Building."
          description="Aether DB turns plain English into production-ready database schemas in seconds. Just describe your application, and get PostgreSQL schemas, TypeScript types, API definitions, and more—instantly."
          background={{ variant: "animated-grid" }}
          avatars={[
            {
              src: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-confident-sof-1772511922535-4e334974.png",              alt: "User 1"
            },
            {
              src: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-startup-found-1772511922841-7e2c6104.png",              alt: "User 2"
            },
            {
              src: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-technical-lea-1772511921950-aa22b771.png",              alt: "User 3"
            }
          ]}
          avatarText="Trusted by 500+ developers"
          buttons={[
            { text: "Try it free", href: "#contact" },
            { text: "See demo", href: "#process" }
          ]}
          buttonAnimation="slide-up"
        />
      </div>

      <div id="what-is" data-section="what-is">
        <MetricSplitMediaAbout
          tag="What is Aether DB?"
          title="Enterprise-Grade Database Infrastructure in Minutes"
          description="Aether DB is an AI-powered database schema generator that transforms natural language descriptions into production-ready PostgreSQL databases. Designed for award-winning teams who demand excellence, it eliminates manual schema design, reduces development time by 90%, and ensures enterprise-level security and performance from day one."
          metrics={[
            {
              value: "90%",              title: "Faster development cycles"
            },
            {
              value: "100%",              title: "Type-safe across your stack"
            }
          ]}
          imageSrc="https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/an-illustration-showing-the-transformati-1772511922816-9b8b2394.png"
          imageAlt="Transformation from manual to automated database setup"
          mediaAnimation="slide-up"
          metricsAnimation="slide-up"
          useInvertedBackground={false}
        />
      </div>

      <div id="process" data-section="process">
        <TimelineProcessFlow
          title="5-Step Process: From Concept to Production"
          description="Experience how Aether DB transforms your database vision into reality"
          tag="Process"
          textboxLayout="default"
          animationType="slide-up"
          items={[
            {
              id: "1",              reverse: false,
              media: (
                <svg
                  className="w-full h-full"
                  viewBox="0 0 200 200"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <defs>
                    <style>
                      {`
                        @keyframes pulse {
                          0%, 100% { opacity: 1; }
                          50% { opacity: 0.5; }
                        }
                        .pulse-circle {
                          animation: pulse 2s infinite;
                        }
                      `}
                    </style>
                  </defs>
                  <circle cx="100" cy="100" r="80" fill="none" stroke="currentColor" strokeWidth="2" />
                  <circle cx="100" cy="100" r="60" className="pulse-circle" fill="currentColor" opacity="0.3" />
                  <text x="100" y="105" textAnchor="middle" fontSize="14" fontWeight="bold" fill="currentColor">
                    Describe
                  </text>
                </svg>
              ),
              content: (
                <>
                  <h3 className="text-xl font-bold mb-2">Step 1: Describe Your App</h3>
                  <p className="text-sm leading-relaxed">
                    Simply tell Aether DB about your application in plain English. Describe your entities, relationships, and business logic as naturally as you would to a colleague.
                  </p>
                </>
              )
            },
            {
              id: "2",              reverse: true,
              media: (
                <svg
                  className="w-full h-full"
                  viewBox="0 0 200 200"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <defs>
                    <style>
                      {`
                        @keyframes slide {
                          0%, 100% { transform: translateX(0); }
                          50% { transform: translateX(20px); }
                        }
                        .slide-arrow {
                          animation: slide 2s infinite;
                        }
                      `}
                    </style>
                  </defs>
                  <rect x="20" y="70" width="60" height="60" fill="currentColor" opacity="0.3" rx="4" />
                  <path className="slide-arrow" d="M 100 100 L 130 100" stroke="currentColor" strokeWidth="3" />
                  <polygon points="130,100 120,95 120,105" fill="currentColor" />
                  <rect x="140" y="70" width="40" height="60" fill="currentColor" opacity="0.5" rx="4" />
                </svg>
              ),
              content: (
                <>
                  <h3 className="text-xl font-bold mb-2">Step 2: AI Analysis</h3>
                  <p className="text-sm leading-relaxed">
                    Our advanced AI engine analyzes your description, identifies all entities, relationships, and constraints, then generates an optimized schema plan.
                  </p>
                </>
              )
            },
            {
              id: "3",              reverse: false,
              media: (
                <svg
                  className="w-full h-full"
                  viewBox="0 0 200 200"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <defs>
                    <style>
                      {`
                        @keyframes rotate {
                          from { transform: rotate(0deg); }
                          to { transform: rotate(360deg); }
                        }
                        .rotate-gear {
                          animation: rotate 4s linear infinite;
                          transform-origin: 100px 100px;
                        }
                      `}
                    </style>
                  </defs>
                  <circle cx="100" cy="100" r="30" fill="none" stroke="currentColor" strokeWidth="4" />
                  <circle cx="100" cy="100" r="15" fill="currentColor" />
                  <circle
                    className="rotate-gear"
                    cx="100"
                    cy="100"
                    r="70"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  />
                </svg>
              ),
              content: (
                <>
                  <h3 className="text-xl font-bold mb-2">Step 3: Schema Generation</h3>
                  <p className="text-sm leading-relaxed">
                    Aether DB generates production-ready PostgreSQL schemas with proper indexes, constraints, and row-level security policies automatically.
                  </p>
                </>
              )
            },
            {
              id: "4",              reverse: true,
              media: (
                <svg
                  className="w-full h-full"
                  viewBox="0 0 200 200"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <defs>
                    <style>
                      {`
                        @keyframes bounce {
                          0%, 100% { transform: translateY(0); }
                          50% { transform: translateY(-20px); }
                        }
                        .bounce-box {
                          animation: bounce 1.5s infinite;
                        }
                      `}
                    </style>
                  </defs>
                  <rect className="bounce-box" x="60" y="60" width="40" height="40" fill="currentColor" opacity="0.4" rx="4" />
                  <rect x="110" y="90" width="60" height="80" fill="currentColor" opacity="0.2" rx="4" />
                  <text x="140" y="140" textAnchor="middle" fontSize="12" fontWeight="bold" fill="currentColor">
                    Types
                  </text>
                </svg>
              ),
              content: (
                <>
                  <h3 className="text-xl font-bold mb-2">Step 4: Complete Code Generation</h3>
                  <p className="text-sm leading-relaxed">
                    Get Zod schemas, TypeScript types, API endpoint definitions, and seed data—all perfectly synchronized with your database schema.
                  </p>
                </>
              )
            },
            {
              id: "5",              reverse: false,
              media: (
                <svg
                  className="w-full h-full"
                  viewBox="0 0 200 200"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <defs>
                    <style>
                      {`
                        @keyframes checkmark {
                          0% { strokeDashoffset: 100; }
                          100% { strokeDashoffset: 0; }
                        }
                        .checkmark {
                          animation: checkmark 1s ease forwards;
                          stroke-dasharray: 100;
                        }
                      `}
                    </style>
                  </defs>
                  <circle cx="100" cy="100" r="70" fill="none" stroke="currentColor" strokeWidth="3" />
                  <path
                    className="checkmark"
                    d="M 70 100 L 90 120 L 130 70"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="4"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              ),
              content: (
                <>
                  <h3 className="text-xl font-bold mb-2">Step 5: Deploy & Scale</h3>
                  <p className="text-sm leading-relaxed">
                    Your production-ready infrastructure is complete. Deploy with confidence knowing your database is secure, optimized, and enterprise-ready.
                  </p>
                </>
              )
            }
          ]}
        />
      </div>

      <div id="features" data-section="features">
        <FeatureCardSixteen
          tag="Traditional vs Aether DB"
          title="Reclaim Hours Every Week"
          description="Stop spending days planning architecture, writing migrations, and syncing types across your codebase."
          negativeCard={{
            items: [
              "Hours planning database schema",              "Writing and debugging SQL migrations",              "Manually creating TypeScript types",              "Syncing types across frontend and backend",              "Managing relational integrity by hand",              "Setting up RLS policies manually"
            ]
          }}
          positiveCard={{
            items: [
              "Instant schema generation",              "Zero-migration SQL setup",              "Auto-generated TypeScript types",              "Perfect type sync everywhere",              "Automatic constraint validation",              "Built-in security policies"
            ]
          }}
          animationType="slide-up"
          textboxLayout="default"
          useInvertedBackground={false}
          buttons={[{ text: "Start building now", href: "#contact" }]}
          buttonAnimation="slide-up"
        />
      </div>

      <div id="metrics" data-section="metrics">
        <MetricCardSeven
          title="Why Teams Choose Aether DB"
          description="Real results from developers building with Aether DB"
          tag="Impact"
          textboxLayout="default"
          useInvertedBackground={false}
          animationType="slide-up"
          metrics={[
            {
              id: "1",              value: "10x",              title: "Faster development",              items: [
                "Database setup in minutes",                "Reduce development cycles",                "Ship features faster"
              ]
            },
            {
              id: "2",              value: "0",              title: "Type mismatches",              items: [
                "Auto-generated consistency",                "End-to-end type safety",                "Catch errors early"
              ]
            },
            {
              id: "3",              value: "100%",              title: "Schema coverage",              items: [
                "Complete documentation",                "All relationships mapped",                "Never miss a constraint"
              ]
            }
          ]}
        />
      </div>

      <div id="testimonials" data-section="testimonials">
        <TestimonialCardThirteen
          title="What Developers Say"
          description="Hear from teams who've transformed their workflow with Aether DB"
          tag="Testimonials"
          textboxLayout="default"
          useInvertedBackground={false}
          showRating={true}
          animationType="slide-up"
          testimonials={[
            {
              id: "1",              name: "Sarah Chen",              handle: "@sarahchen",              testimonial:
                "Aether DB cut our database setup time from 2 days to 10 minutes. The generated TypeScript types alone saved us countless hours of debugging.",              rating: 5,
              imageSrc:
                "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-confident-sof-1772511922535-4e334974.png",              imageAlt: "Sarah Chen"
            },
            {
              id: "2",              name: "Marcus Rodriguez",              handle: "@mrodriguez",              testimonial:
                "Finally, a tool that understands what developers actually need. No more manual schema creation, no more type mismatches. Just describe what you want.",              rating: 5,
              imageSrc:
                "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-startup-found-1772511922841-7e2c6104.png",              imageAlt: "Marcus Rodriguez"
            },
            {
              id: "3",              name: "Emma Thompson",              handle: "@emmathompson",              testimonial:
                "The RLS policies and security constraints are production-ready out of the box. This is enterprise-grade infrastructure in minutes.",              rating: 5,
              imageSrc:
                "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-technical-lea-1772511921950-aa22b771.png",              imageAlt: "Emma Thompson"
            },
            {
              id: "4",              name: "Alex Kumar",              handle: "@alexkumar",              testimonial:
                "We went from prototyping to production faster than ever. Aether DB handles the boring database stuff so we can focus on features.",              rating: 5,
              imageSrc:
                "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/professional-headshot-of-a-product-manag-1772511922206-877ffab8.png",              imageAlt: "Alex Kumar"
            }
          ]}
        />
      </div>

      <div id="faq" data-section="faq">
        <FaqBase
          title="Frequently Asked Questions"
          description="Everything you need to know about Aether DB"
          tag="Help"
          textboxLayout="default"
          useInvertedBackground={false}
          faqsAnimation="slide-up"
          animationType="smooth"
          faqs={[
            {
              id: "1",              title: "How does Aether DB generate database schemas?",              content:
                "Simply describe your application in plain English. Our AI understands your requirements and generates optimized PostgreSQL schemas with proper indexes, constraints, foreign keys, and RLS policies. You get production-ready code instantly."
            },
            {
              id: "2",              title: "What exactly do I get when I use Aether DB?",              content:
                "You receive: PostgreSQL schema with indexes and constraints, Zod schemas for validation, TypeScript types for your entire database, RESTful API endpoint definitions with typed request/response bodies, realistic seed data with relational integrity, and an AI explanation of every architectural decision."
            },
            {
              id: "3",              title: "Is the generated code production-ready?",              content:
                "Yes. All generated schemas include proper foreign key relationships, unique constraints, check constraints, row-level security policies, and performance indexes. The code is audited and optimized for production environments."
            },
            {
              id: "4",              title: "Can I customize the generated schema?",              content:
                "Absolutely. The generated code is yours to modify. You can edit schemas, adjust constraints, add custom columns, or refine RLS policies. Aether DB gives you the foundation—you maintain full control."
            },
            {
              id: "5",              title: "What databases are supported?",              content:
                "Currently, Aether DB generates PostgreSQL schemas. MySQL and other database support is coming soon."
            },
            {
              id: "6",              title: "Do you store my project descriptions?",              content:
                "We take privacy seriously. Your project descriptions are processed but not stored in our system. Enterprise users can opt for on-premise deployment."
            }
          ]}
        />
      </div>

      <div id="contact" data-section="contact">
        <ContactSplit
          tag="Get Started"
          title="Start Building Faster Today"
          description="Sign up for free and generate your first production-ready schema in under 2 minutes."
          background={{ variant: "animated-grid" }}
          useInvertedBackground={false}
          imageSrc="https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AQ53gfKdS0YSH1q5OGpM06AnUi/an-illustration-of-a-person-working-on-a-1772511922490-57b835bf.png"
          imageAlt="Developer working with Aether DB"
          mediaAnimation="slide-up"
          mediaPosition="right"
          inputPlaceholder="you@company.com"
          buttonText="Get Free Access"
          termsText="By signing up, you agree to our Terms of Service and Privacy Policy. We respect your data."
        />
      </div>

      <div id="footer" data-section="footer">
        <FooterLogoEmphasis
          logoText="Aether DB"
          columns={[
            {
              items: [
                { label: "What is Aether DB", href: "#what-is" },
                { label: "How It Works", href: "#process" },
                { label: "Features", href: "#features" }
              ]
            },
            {
              items: [
                {
                  label: "Documentation",                  href: "https://docs.aether-db.com"
                },
                { label: "API Reference", href: "https://docs.aether-db.com/api" },
                { label: "GitHub", href: "https://github.com/aether-db" }
              ]
            },
            {
              items: [
                { label: "Blog", href: "https://blog.aether-db.com" },
                { label: "Twitter", href: "https://twitter.com/aether_db" },
                { label: "Discord", href: "https://discord.gg/aether-db" }
              ]
            },
            {
              items: [
                { label: "Privacy Policy", href: "#" },
                { label: "Terms of Service", href: "#" },
                { label: "Contact", href: "#contact" }
              ]
            }
          ]}
        />
      </div>
    </ThemeProvider>
  );
}
