"use client";

import { motion } from "framer-motion";
import { ArrowRight, Github, Linkedin, Mail, ChevronDown, MessageCircle, Zap } from "lucide-react";
import dynamic from "next/dynamic";
import { HeroSection as HeroData } from "@/lib/constant";
import { useEffect, useState } from "react";
import TerminalWindow from "@/components/TerminalWindow";

// Dynamic import for Lottie animation
const LottieAnimation = dynamic(
  () => import("lottie-react").then((mod) => mod.default),
  {
    ssr: false,
    loading: () => (
      <div className="w-20 h-20 animate-pulse bg-accent/20 rounded-xl" />
    ),
  }
);

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.12,
      delayChildren: 0.2,
    },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 24 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.5, ease: "easeOut" },
  },
};

export function HeroSection() {
  const [loadingAnimation, setLoadingAnimation] = useState(null);
  const [isDark, setIsDark] = useState(false);
  const [showScrollIndicator, setShowScrollIndicator] = useState(true);

  useEffect(() => {

    fetch("/lottie/loading.json")
      .then((res) => res.json())
      .then((data) => setLoadingAnimation(data))
      .catch((err) =>
        console.error("Failed to load Lottie animation:", err)
      );

    // Check dark mode
    const checkDarkMode = () => {
      setIsDark(document.documentElement.classList.contains('dark'));
    };

    checkDarkMode();

    // Listen for theme changes
    const observer = new MutationObserver(checkDarkMode);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class']
    });

    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      const scrollTop = window.scrollY;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;
      
      // Hide scroll indicator when user is at the bottom (within 50px of bottom)
      if (scrollTop + windowHeight >= documentHeight - 50) {
        setShowScrollIndicator(false);
      } else {
        setShowScrollIndicator(true);
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <section
      id="hero"
      aria-labelledby="hero-title"
      className="relative min-h-screen flex flex-col items-center justify-center overflow-hidden"
    >
      {/* Background effects */}
      <div
        className="absolute inset-0 bg-grid opacity-100"
        aria-hidden="true"
      />
      <div
        className="absolute inset-0 bg-gradient-to-b from-background via-background/95 to-background"
        aria-hidden="true"
      />

      {/* Mobile photo background */}
      <div
        className="absolute inset-0 lg:hidden opacity-10"
        style={{
          backgroundImage: `url(${HeroData.image})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat'
        }}
        aria-hidden="true"
      />

      {/* Blur orbs */}
      <div
        className="absolute top-1/4 left-1/4 w-96 h-96 bg-accent/8 rounded-full blur-[120px] pointer-events-none"
        aria-hidden="true"
      />
      <div
        className="absolute bottom-1/3 right-1/4 w-80 h-80 bg-purple-500/6 rounded-full blur-[100px] pointer-events-none"
        aria-hidden="true"
      />
      <div
        className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-accent/4 rounded-full blur-[150px] pointer-events-none"
        aria-hidden="true"
      />

      <div className="relative z-10 max-w-7xl mx-auto px-6 lg:px-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center min-h-[70vh] py-20 lg:py-0 lg:gap-16">
          <motion.div
            variants={containerVariants}
            initial="hidden"
            animate="visible"
            className="text-center lg:text-left flex flex-col items-center lg:items-start"
          >
            {/* Status badge */}
            <motion.div variants={itemVariants} className="mb-8">
              <p
                role="status"
                aria-live="polite"
                className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-border bg-accent/10 text-accent text-sm font-medium"
              >
                <span
                  className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse-slow"
                  aria-hidden="true"
                />
                {HeroData.badge || "Available for opportunities"}
              </p>
            </motion.div>

            {/* Lottie animation */}
            <motion.div 
              variants={itemVariants} 
              className="-mt-8 block lg:hidden overflow-hidden rounded-md"
            >
              {loadingAnimation && (
                <LottieAnimation
                  animationData={loadingAnimation}
                  loop
                  autoplay
                  className="w-[300px] h-[200px] object-cover"
                />
              )}
            </motion.div>

            {/* Main headline */}
            <motion.h1
              id="hero-title"
              variants={itemVariants}
              className="font-display font-bold text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.05] tracking-tight mb-6"
            >
              <span className="text-foreground">
                {HeroData.headline || "Building Systems"}
              </span>
              <br />
              <span className="gradient-text">
                {HeroData.headline2 || "That Scale."}
              </span>
            </motion.h1>

            {/* Tagline */}
            <motion.p
              variants={itemVariants}
              className="text-lg md:text-xl text-foreground-muted mb-4 font-light leading-relaxed max-w-2xl"
            >
              {HeroData.tagline1 ||
                "Senior Fullstack Engineer — Next.js & NestJS Specialist"}
            </motion.p>

            <motion.p
              variants={itemVariants}
              className="text-base text-foreground-subtle mb-10 leading-relaxed max-w-xl"
            >
              {HeroData.tagline2 ||
                "I architect and ship production-grade web applications with a focus on clean architecture, performance, and developer experience."}
            </motion.p>

            {/* CTA Buttons */}
            <motion.nav
              aria-label="Primary Actions"
              variants={itemVariants}
              className="flex flex-wrap items-center justify-center lg:justify-start gap-4 mb-14"
            >
              <a
                href="#projects"
                className="group inline-flex items-center gap-2 px-6 py-3 bg-accent text-white font-semibold rounded-xl hover:bg-accent/90 transition-all hover:shadow-glow hover:-translate-y-0.5 duration-200"
              >
                View Projects
                <ArrowRight
                  size={16}
                  className="group-hover:translate-x-1 transition-transform"
                  aria-hidden="true"
                />
              </a>
              <a
                href="#contact"
                className="inline-flex items-center gap-2 px-6 py-3 bg-surface-elevated border border-border text-foreground font-medium rounded-xl hover:border-accent/40 hover:bg-surface-elevated/80 transition-all hover:-translate-y-0.5 duration-200"
              >
                <Mail size={16} className="text-accent" aria-hidden="true" />
                Contact Me
              </a>
            </motion.nav>

            {/* Social links */}
            <motion.nav
              aria-label="Social Media Profiles"
              variants={itemVariants}
              className="flex items-center justify-center lg:justify-start gap-4"
            >
              <ul className="flex items-center gap-4 m-0 p-0 list-none">
                <li>
                  <a
                    href="https://github.com/Dzuuul"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block p-2.5 rounded-xl border border-border hover:border-accent/40 hover:bg-surface-elevated text-foreground-muted hover:text-foreground transition-all hover:-translate-y-0.5 duration-200"
                    aria-label="GitHub Profile"
                  >
                    <Github size={18} aria-hidden="true" />
                  </a>
                </li>
                <li>
                  <a
                    href="https://www.linkedin.com/in/dzulfikrimaulana"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block p-2.5 rounded-xl border border-border hover:border-accent/40 hover:bg-surface-elevated text-foreground-muted hover:text-foreground transition-all hover:-translate-y-0.5 duration-200"
                    aria-label="LinkedIn Profile"
                  >
                    <Linkedin size={18} aria-hidden="true" />
                  </a>
                </li>
                <li>
                  <a
                    href="https://wa.me/6285163616363?text=Hi%20Fikri,%0D%0AI%20am%20[Name]%20from%20[Company/Organization%20Name].%0D%0AI%20recently%20explored%20your%20portfolio%20and%20was%20impressed%20by%20your%20work%20as%20a%20Fullstack%20Developer.%0D%0AI%20would%20like%20to%20discuss%20a%20potential%20opportunity%20with%20you,%20whether%20it%20be%20for%20a%20career%20role%20within%20our%20team%20or%20a%20professional%20collaboration%20on%20an%20upcoming%20project.%0D%0AAre%20you%20available%20for%20a%20brief%20introductory%20call%20or%20a%20chat%20sometime%20this%20week%20to%20discuss%20this%20further?%0D%0A%0D%0ABest%20regards,%0D%0A[Name]%0D%0A[LinkedIn%20Profile/Contact%20Info]"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block p-2.5 rounded-xl border border-border hover:border-accent/40 hover:bg-surface-elevated text-foreground-muted hover:text-foreground transition-all hover:-translate-y-0.5 duration-200"
                    aria-label="WhatsApp Contact"
                  >
                    <MessageCircle size={18} aria-hidden="true" />
                  </a>
                </li>
              </ul>

              <div className="w-px h-5 bg-border mx-1" aria-hidden="true" />

              <span className="text-foreground-subtle text-sm font-mono">
                3+ yrs experience
              </span>
            </motion.nav>
          </motion.div>

          {/* Right Section: Photo - Desktop Only */}
          <motion.div
            variants={itemVariants}
            initial="hidden"
            animate="visible"
            className="relative hidden lg:flex justify-end"
          >
            <motion.div
              className="relative group max-w-xs sm:max-w-md w-full aspect-square"
              whileHover={{ scale: 1.02 }}
              transition={{ duration: 0.3, ease: "easeOut" }}
            >
              {/* Window frame */}
              <div className="relative h-full w-full rounded-lg border border-border bg-surface-elevated shadow-2xl overflow-hidden">

                {/* Window header */}
                <div className="flex items-center justify-between px-3 py-2 border-b border-border bg-surface-elevated/70">
                  <div className="flex gap-2">
                    <div className="w-3 h-3 bg-red-500 rounded-full" />
                    <div className="w-3 h-3 bg-yellow-500 rounded-full" />
                    <div className="w-3 h-3 bg-green-500 rounded-full" />
                  </div>
                  <span className="text-xs text-foreground-muted">
                    portfolio.jpg
                  </span>
                </div>

                {/* Image content */}
                <div className="flex-1 flex items-center justify-center bg-surface">
                  <img
                    src={HeroData.image}
                    alt="Professional portrait"
                    className="max-w-full max-h-full object-contain group-hover:scale-105 transition-transform duration-700"
                  />
                </div>
              </div>

              {/* Floating card decor */}
              <div className="absolute -bottom-8 -left-8 rounded-xl bg-surface-elevated border border-border p-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-accent/10 text-accent">
                    <Zap
                      size={24}
                      strokeWidth={2}
                      aria-hidden="true"
                    />
                  </div>
                  <div>
                    <p className="text-lg font-semibold text-foreground">10+ Projects</p>
                    <p className="text-sm text-foreground-muted">Completed successfully</p>
                  </div>
                </div>
              </div>

              {/* Floating card decor */}
              <div className="absolute -top-12 -right-8 rounded-xl bg-surface-elevated border border-border p-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-accent/10 text-accent">
                    <Zap
                      size={24}
                      strokeWidth={2}
                      aria-hidden="true"
                    />
                  </div>
                  <div>
                    <p className="text-lg font-semibold text-foreground">Production Systems</p>
                    <p className="text-sm text-foreground-muted">Built & Maintained</p>
                  </div>
                </div>
              </div>

              {/* Terminal Window */}
              <div className="absolute -bottom-[45px] -right-[100px]">
                <TerminalWindow />
              </div>
            </motion.div>
          </motion.div>
        </div>
      </div>

      {/* Scroll indicator */}
      {showScrollIndicator && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 1.5, duration: 0.5 }}
          className="fixed -bottom-3 left-1/2 transform -translate-x-1/2 z-50"
          aria-hidden="true"
        >
          {/* Rounded rectangle container with content inside */}
          <div className="w-32 h-16 rounded-t-2xl border border-border bg-surface-elevated/80 backdrop-blur-sm flex flex-col items-center justify-center -gap-1 shadow-lg">
            <span className="text-foreground-subtle text-xs font-mono tracking-widest uppercase">
              Scroll Down
            </span>
            <motion.div
              animate={{ y: [0, 4, 0] }}
              transition={{ duration: 1.5, repeat: Infinity, ease: "easeInOut" }}
              className="flex items-center justify-center"
            >
              <ChevronDown size={16} className="text-accent" />
            </motion.div>
          </div>
        </motion.div>
      )}
    </section>
  );
}
