"use client";

import { useEffect, useState } from "react";
import { Link as IntlLink } from "@/i18n/navigation";
import { GridLines, StarField, GlobeAnimation } from "../index";
import { useTranslations } from "next-intl";

export default function HeroSection() {
  const t = useTranslations("heroSection");

  const installScript = "curl -sSL https://raw.githubusercontent.com/kubestellar/console/main/start.sh | bash";

  const [displayedText, setDisplayedText] = useState("");
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(installScript);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy text:", err);
    }
  };
  useEffect(() => {
    let typingInterval: NodeJS.Timeout;
    let restartTimeout: NodeJS.Timeout;
  
    const startTyping = () => {
      let index = 0;
      setDisplayedText("");
  
      typingInterval = setInterval(() => {
        index++;
        setDisplayedText(installScript.slice(0, index));
  
        if (index >= installScript.length) {
          clearInterval(typingInterval);
  
          // Wait 30 seconds before restarting
          restartTimeout = setTimeout(() => {
            startTyping();
          }, 30000);
        }
      }, 35);
    };
  
    startTyping();
  
    // Animated Counters
    const animateCounters = () => {
      const counters = document.querySelectorAll(".counter");
  
      counters.forEach((counter) => {
        const target = parseInt(counter.getAttribute("data-target") || "0", 10);
  
        const duration = 2000;
        const step = target / (duration / 16);
  
        let current = 0;
  
        const timer = setInterval(() => {
          current += step;
  
          if (current >= target) {
            current = target;
            clearInterval(timer);
          }
  
          counter.textContent = Math.floor(current).toString();
        }, 16);
      });
    };
  
    animateCounters();
  
    return () => {
      clearInterval(typingInterval);
      clearTimeout(restartTimeout);
    };
  }, [installScript]);

  return (
    <section className="relative overflow-hidden bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 text-white min-h-screen flex items-center">
      {/* Animated Background Universe */}
      <div className="absolute inset-0 z-0">
        {/*!-- Floating Nebula Clouds */}
        {/* Dynamic Star Field */}
        <div className="absolute inset-0 bg-[#0a0a0a]">
          <StarField density="medium" showComets={true} cometCount={8} />
        </div>

        {/* Interactive Grid Network */}
        <div className="absolute inset-0">
          <GridLines verticalLines={15} horizontalLines={18} />
        </div>

        {/* Floating Data Particles */}
        <div className="absolute inset-0">
          <div
            className="data-particle"
            style={{ "--delay": "0s" } as React.CSSProperties}
          ></div>
          <div
            className="data-particle"
            style={{ "--delay": "1s" } as React.CSSProperties}
          ></div>
          <div
            className="data-particle"
            style={{ "--delay": "2s" } as React.CSSProperties}
          ></div>
          <div
            className="data-particle"
            style={{ "--delay": "3s" } as React.CSSProperties}
          ></div>
          <div
            className="data-particle"
            style={{ "--delay": "4s" } as React.CSSProperties}
          ></div>
          <div
            className="data-particle"
            style={{ "--delay": "5s" } as React.CSSProperties}
          ></div>
        </div>
      </div>

      {/* Main Content Container */}
      <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 lg:py-12">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-10 items-center">
          {/* Left Column: Interactive Content */}
          <div className="hero-content space-y-5 sm:space-y-6 lg:space-y-7 flex flex-col">
            {/* Heading now sits in the left column so globe and heading share the same top alignment on desktop */}
            <div className="heading-container pt-0">
              <h1 className="text-4xl sm:text-5xl lg:text-6xl xl:text-7xl font-black tracking-tight leading-[1.03]">
                <span className="block text-white mb-2 animate-text-reveal pt-1">
                  <span className="text-gradient lg:whitespace-nowrap">{t("line1")}</span>
                </span>
                <span className="block animate-text-reveal">
                  <span className="text-gradient-animated lg:whitespace-nowrap">{t("line2")}</span>
                </span>
                <span className="block animate-text-reveal [animation-delay:0.4s]">
                  <span className="text-gradient-animated lg:whitespace-nowrap">{t("line3")}</span>
                </span>
              </h1>
            </div>

            {/* Paragraph with fade-in-up effect and delay */}
            <p className="sm:text-xl text-gray-300 max-w-2xl leading-snug animate-fade-in-up opacity-0 [animation-delay:0.6s] [animation-fill-mode:forwards]">
              {t("subtitle")}
            </p>

            {/* Get Started Heading */}
            <h3 className="text-xl font-bold text-white">
              Get Started with{" "}
              <span className="text-gradient animated-gradient bg-gradient-to-r from-blue-400 via-purple-400 to-blue-400">
                KubeStellar Console
              </span>
            </h3>

            {/* Install Command */}
            <div className="command-center-container">
              <div className="bg-black/50 backdrop-blur-xl border border-green-500/20 rounded-2xl p-5 shadow-2xl">

                <div className="flex items-center justify-between">

                  <div className="flex items-center flex-1 overflow-hidden">

                    <span className="text-green-400 font-mono mr-3 select-none">
                      $
                    </span>

                    <code className="font-mono text-green-300 text-sm whitespace-nowrap overflow-x-auto scrollbar-hide">
                      {displayedText}

                      <span className="ml-0.5 inline-block w-[2px] h-5 bg-green-400 animate-pulse align-middle"></span>
                    </code>

                  </div>

                  <button
                    onClick={handleCopy}
                    className="ml-4 p-2 rounded-lg hover:bg-white/10 transition-all duration-300 flex-shrink-0"
                  >
                    {copied ? (
                      <svg
                        className="w-5 h-5 text-green-400"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M5 13l4 4L19 7"
                        />
                      </svg>
                    ) : (
                      <svg
                        className="w-5 h-5 text-sky-400 hover:text-sky-300 transition-colors"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                        />
                      </svg>
                    )}
                  </button>

                </div>

              </div>
            </div>

            {/* Console Links */}
            <div className="mt-4 flex flex-wrap items-center gap-3 animate-btn-float" style={{ animationDelay: "0.8s" }}>
              <a
                href="https://console.kubestellar.io"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 rounded-lg border border-purple-400/80 bg-transparent px-4 py-2.5 text-sm sm:text-base font-semibold text-purple-200 transition-all duration-200 hover:border-purple-300 hover:bg-purple-400/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-900"
              >
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                {t("buttonInstall")}
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                </svg>
              </a>
              <IntlLink
                href="/docs/console/readme"
                className="inline-flex items-center justify-center gap-2 rounded-lg border border-sky-400/80 bg-transparent px-4 py-2.5 text-sm sm:text-base font-semibold text-sky-200 transition-all duration-200 hover:border-sky-300 hover:bg-sky-400/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-900"
              >
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                </svg>
                {t("buttonDocs")}
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                </svg>
              </IntlLink>
            </div>
          </div>

          {/* Right Column: Globe Animation */}
          <div className="globe-animation-container relative h-[360px] sm:h-[430px] lg:h-[560px] xl:h-[620px] flex items-center justify-center lg:justify-end self-center lg:translate-x-4 xl:translate-x-6">
            <GlobeAnimation
              width="100%"
              height="100%"
              className="h-full w-full max-w-[680px] rounded-xl overflow-hidden"
              showLoader={true}
              enableControls={true}
              enablePan={false}
              autoRotate={true}
              style={{
                filter: "drop-shadow(0 25px 50px rgba(59, 130, 246, 0.3))",
              }}
            />
          </div>
        </div>
      </div>
    </section>
  );
}