"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Search, MapPin, Check, Mail } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { trendingSearches } from "@/data/mockData.landing";

// ─── Rotating keywords ──────────────────────────────────────────────────────
const ROTATING_KEYWORDS = [
    { word: "Tech",             color: "text-primary" },
    { word: "Marketing",        color: "text-violet-500" },
    { word: "Sales",            color: "text-emerald-500" },
    { word: "Design",           color: "text-pink-500" },
    { word: "Customer Service", color: "text-amber-500" },
    { word: "Data",             color: "text-cyan-500" },
    { word: "AI",               color: "text-indigo-500" },
    { word: "Finance",          color: "text-rose-500" },
    { word: "HR",               color: "text-teal-500" },
    { word: "Engineering",      color: "text-blue-600" },
];



export function Hero() {
    const router = useRouter();
    const searchParams = useSearchParams();

    const [query, setQuery] = useState(searchParams.get("q") || "");
    const [location, setLocation] = useState(searchParams.get("l") || "");

    // ─── Rotating keyword state ─────────────────────────────────────────────
    // IMPORTANT: Always start at index 0 on both server and client so SSR
    // and the first client render are identical (avoids hydration mismatch).
    // We randomize the starting index only after mount (client-only useEffect).
    const [kwIndex, setKwIndex] = useState(0);
    const currentKw = ROTATING_KEYWORDS[kwIndex];

    useEffect(() => {
        // Pick a random starting keyword after hydration, then rotate every 2.8 s
        const startIndex = Math.floor(Math.random() * ROTATING_KEYWORDS.length);
        setKwIndex(startIndex);

        const id = setInterval(() => {
            setKwIndex(i => (i + 1) % ROTATING_KEYWORDS.length);
        }, 2800);
        return () => clearInterval(id);
    }, []);

    // ─── Search handlers ──────────────────────────────────────────────────
    const inputRef = useRef<HTMLInputElement>(null);

    const handleSearch = (q = query, l = location) => {
        const params = new URLSearchParams();
        if (q) params.set("q", q);
        if (l) params.set("l", l);
        router.push(`/jobs?${params.toString()}`);
    };

    /** Navigate to /jobs with the clicked term pre-filled */
    const handleTrendingClick = (term: string) => {
        router.push(`/jobs?q=${encodeURIComponent(term)}`);
    };

    return (
        <section className="relative pt-44 pb-32 hero-gradient overflow-hidden min-h-[90vh] flex flex-col justify-center">
            {/* Background Blobs */}
            <div className="absolute inset-0 z-0 overflow-hidden pointer-events-none">
                <motion.div
                    animate={{ x: [0, 30, -20, 0], y: [0, -50, 20, 0], scale: [1, 1.1, 0.9, 1] }}
                    transition={{ duration: 7, repeat: Infinity, ease: "easeInOut" }}
                    className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-primary/10 rounded-full mix-blend-multiply blur-3xl opacity-70"
                />
                <motion.div
                    animate={{ x: [0, -30, 20, 0], y: [0, 50, -20, 0], scale: [1, 1.2, 0.8, 1] }}
                    transition={{ duration: 7, repeat: Infinity, ease: "easeInOut", delay: 2 }}
                    className="absolute top-[-10%] right-[-10%] w-[40%] h-[40%] bg-accent-yellow/20 rounded-full mix-blend-multiply blur-3xl opacity-70"
                />
                <motion.div
                    animate={{ x: [0, 20, -30, 0], y: [0, -20, 40, 0], scale: [1, 0.9, 1.1, 1] }}
                    transition={{ duration: 7, repeat: Infinity, ease: "easeInOut", delay: 4 }}
                    className="absolute bottom-[-20%] left-[20%] w-[50%] h-[50%] bg-blue-300/20 rounded-full mix-blend-multiply blur-3xl opacity-70"
                />
            </div>

            <div className="max-w-7xl mx-auto px-6 text-center relative z-10 w-full">
                {/* Badge */}
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 text-primary text-xs font-bold uppercase tracking-widest mb-8"
                >
                    <span className="relative flex h-2 w-2">
                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
                        <span className="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
                    </span>
                    Connecting 10k+ Monthly Talents
                </motion.div>

                {/* Headline with rotating keyword */}
                <motion.h1
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.1 }}
                    className="text-5xl md:text-7xl font-extrabold text-deep-navy mb-6 leading-[1.1] tracking-tight max-w-4xl mx-auto"
                >
                    Find Your Next Big <br /> Opportunity in{" "}

                    {/* Rotating keyword slot — fixed min-width prevents layout shift */}
                    <span className="relative inline-block min-w-[220px] md:min-w-[280px]">
                        <AnimatePresence mode="wait">
                            <motion.span
                                key={currentKw.word}
                                initial={{ opacity: 0, y: 20, filter: "blur(8px)" }}
                                animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                                exit={{ opacity: 0, y: -20, filter: "blur(8px)" }}
                                transition={{ duration: 0.45, ease: "easeInOut" }}
                                className={`${currentKw.color} inline-block`}
                            >
                                {currentKw.word}
                            </motion.span>
                        </AnimatePresence>

                        {/* Animated underline that resets on each keyword change */}
                        <AnimatePresence mode="wait">
                            <motion.div
                                key={`underline-${currentKw.word}`}
                                initial={{ width: 0 }}
                                animate={{ width: "100%" }}
                                exit={{ opacity: 0 }}
                                transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
                                className="absolute -bottom-2 left-0 h-1 bg-accent-yellow rounded-full"
                            />
                        </AnimatePresence>
                    </span>
                </motion.h1>

                <motion.p
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.2 }}
                    className="text-lg text-slate-600 mb-12 max-w-2xl mx-auto leading-relaxed"
                >
                    Proten Connect bridges the gap between top-tier talent and world-class companies. No more endless searching—just perfect matches.
                </motion.p>

                {/* Search bar */}
                <motion.div
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.6, delay: 0.3 }}
                    className="max-w-5xl mx-auto relative group"
                >
                    <div className="absolute -inset-1 bg-gradient-to-r from-primary/20 to-accent-yellow/20 rounded-2xl blur opacity-25 group-hover:opacity-50 transition duration-1000 group-hover:duration-200"></div>

                    <div className="relative bg-white p-2 rounded-2xl shadow-xl shadow-slate-200/50 border border-slate-100 mb-6">
                        <div className="flex flex-col md:flex-row items-center w-full">
                            <div className="flex-1 flex items-center px-4 py-3 w-full border-b md:border-b-0 md:border-r border-slate-100">
                                <Search className="text-slate-400 mr-3 h-5 w-5 shrink-0" />
                                <input
                                    ref={inputRef}
                                    className="w-full bg-transparent border-none focus:ring-0 text-slate-900 placeholder-slate-400 text-base outline-none"
                                    placeholder="Job titles, keywords, or company..."
                                    type="text"
                                    value={query}
                                    onChange={(e) => setQuery(e.target.value)}
                                    onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                                />
                            </div>
                            <div className="flex-1 flex items-center px-4 py-3 w-full">
                                <MapPin className="text-slate-400 mr-3 h-5 w-5 shrink-0" />
                                <input
                                    className="w-full bg-transparent border-none focus:ring-0 text-slate-900 placeholder-slate-400 text-base outline-none"
                                    placeholder="Remote, New York, London..."
                                    type="text"
                                    value={location}
                                    onChange={(e) => setLocation(e.target.value)}
                                    onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                                />
                            </div>
                            <button
                                onClick={() => handleSearch()}
                                className="w-full md:w-auto px-10 py-4 bg-accent-yellow hover:bg-yellow-400 text-deep-navy font-extrabold rounded-xl transition-all flex items-center justify-center gap-2 shrink-0"
                            >
                                Search Jobs
                            </button>
                        </div>
                    </div>

                    {/* Trending keyword chips — clickable, fill search, auto-submit */}
                    <div className="flex flex-wrap items-center justify-center gap-2 lg:gap-3 text-left">
                        <span className="text-[14px] font-bold text-slate-700 font-display mr-2">Trending jobs:</span>
                        {trendingSearches.map((term, index) => (
                            <motion.button
                                key={index}
                                whileHover={{ scale: 1.05 }}
                                whileTap={{ scale: 0.96 }}
                                onClick={() => handleTrendingClick(term)}
                                className={`px-4 py-1.5 text-[13px] font-display rounded-full transition-all duration-200 cursor-pointer border ${
                                    query === term
                                        ? "bg-primary text-white border-primary shadow-md shadow-primary/20"
                                        : "bg-white/80 text-slate-600 border-slate-200 hover:bg-primary hover:text-white hover:border-primary"
                                }`}
                            >
                                {term}
                            </motion.button>
                        ))}
                    </div>
                </motion.div>
            </div>

            {/* Floating Decorative Elements */}
            <motion.div
                initial={{ opacity: 0, scale: 0.8, x: -20, rotate: -15 }}
                animate={{
                    opacity: 1,
                    scale: 1,
                    x: 0,
                    rotate: [-5, -8, -5],
                    y: [0, -15, 0]
                }}
                transition={{
                    opacity: { duration: 0.5, delay: 0.8 },
                    scale: { duration: 0.5, delay: 0.8, type: "spring" },
                    y: { duration: 5, repeat: Infinity, ease: "easeInOut" },
                    rotate: { duration: 6, repeat: Infinity, ease: "easeInOut" }
                }}
                className="absolute top-1/4 left-[5%] p-4 bg-white rounded-2xl shadow-xl shadow-slate-200/50 border border-slate-100 hidden xl:block z-10 origin-bottom-right"
            >
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center text-green-600">
                        <Check className="h-5 w-5" />
                    </div>
                    <div>
                        <p className="text-xs text-slate-400 font-bold uppercase">Matched</p>
                        <p className="text-sm font-bold text-deep-navy">Senior Designer</p>
                    </div>
                </div>
            </motion.div>

            <motion.div
                initial={{ opacity: 0, scale: 0.8, x: 20, rotate: 15 }}
                animate={{
                    opacity: 1,
                    scale: 1,
                    x: 0,
                    rotate: [5, 10, 5],
                    y: [0, -20, 0]
                }}
                transition={{
                    opacity: { duration: 0.5, delay: 1 },
                    scale: { duration: 0.5, delay: 1, type: "spring" },
                    y: { duration: 6, repeat: Infinity, ease: "easeInOut", delay: 1 },
                    rotate: { duration: 7, repeat: Infinity, ease: "easeInOut", delay: 1 }
                }}
                className="absolute bottom-1/4 right-[5%] p-4 bg-white rounded-2xl shadow-xl shadow-slate-200/50 border border-slate-100 hidden xl:block z-10 origin-bottom-left"
            >
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center text-primary">
                        <Mail className="h-5 w-5" />
                    </div>
                    <div>
                        <p className="text-xs text-slate-400 font-bold uppercase">Interview Request</p>
                        <p className="text-sm font-bold text-deep-navy">Google UX Team</p>
                    </div>
                </div>
            </motion.div>
        </section>
    );
}
