"use client";

import { useState, useRef, useEffect } from "react";
import { Switch } from "@/components/ui/switch";
import { motion, Variants } from "framer-motion";
import { Shield, EyeOff } from "lucide-react";
import { Dictionary } from "@/lib/IDict";
import { CyberButton } from "../ui/cyber-button";
import { NetrunnerMatrix } from "../graphics/NetrunnerMatrix";
import { useTheme } from "next-themes";

function CyberEye({
  isClosed,
  vpnOn,
  targetX,
  targetY,
}: {
  isClosed: boolean;
  vpnOn: boolean;
  targetX: number;
  targetY: number;
}) {
  const eyeRef = useRef<HTMLDivElement>(null);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [direction, setDirection] = useState("center");

  // Теперь глаз только вычисляет углы на основе переданных ему координат
  useEffect(() => {
    if (isClosed || !eyeRef.current) return;
    const rect = eyeRef.current.getBoundingClientRect();
    const eyeCenterX = rect.left + rect.width / 2;
    const eyeCenterY = rect.top + rect.height / 2;
    const dx = targetX - eyeCenterX;
    const dy = targetY - eyeCenterY;

    if (Math.abs(dx) < 30 && Math.abs(dy) < 30) {
      setDirection("center");
    } else if (Math.abs(dx) > Math.abs(dy)) {
      setDirection(dx > 0 ? "right" : "left");
    } else {
      setDirection(dy > 0 ? "down" : "up");
    }

    const angle = Math.atan2(dy, dx);
    const maxRadius = 22;
    // Чуть усилили множитель (0.15), чтобы глаза были более "отзывчивыми"
    const distance = Math.min(maxRadius, Math.hypot(dx, dy) * 0.15);
    setOffset({ x: Math.cos(angle) * distance, y: Math.sin(angle) * distance });
  }, [targetX, targetY, isClosed]);

  const eyeVariants: Variants = {
    open: {
      height: 72,
      width: 120,
      borderRadius: 36,
      borderWidth: 4,
      transition: { type: "spring", stiffness: 450, damping: 12 },
    },
    closed: {
      height: 6,
      width: 140,
      borderRadius: 8,
      borderWidth: 3,
      transition: { type: "spring", stiffness: 600, damping: 14 },
    },
  };

  const borderColor = vpnOn
    ? "border-purple-600 dark:border-primary shadow-[0_0_15px_rgba(139,61,255,0.3)]"
    : "border-cyan-600 dark:border-secondary shadow-[0_0_15px_rgba(0,229,242,0.3)]";

  return (
    <motion.div
      ref={eyeRef}
      variants={eyeVariants}
      initial="open"
      animate={isClosed ? "closed" : "open"}
      className={`relative flex items-center justify-center overflow-hidden bg-background ${borderColor} z-10 select-none`}
    >
      <motion.div
        animate={{
          x: isClosed ? 0 : offset.x,
          y: isClosed ? 0 : offset.y,
          scale: isClosed ? 0.3 : 1,
          opacity: isClosed ? 0 : 1,
        }}
        transition={{ type: "tween", ease: "easeOut", duration: 0.1 }}
        className="relative flex items-center justify-center text-foreground pointer-events-none"
      >
        <span
          className={`absolute -top-4 text-xs transition-opacity ${direction === "up" ? "opacity-100 scale-125" : "opacity-20"}`}
        >
          ▴
        </span>
        <span
          className={`absolute -bottom-4 text-xs transition-opacity ${direction === "down" ? "opacity-100 scale-125" : "opacity-20"}`}
        >
          ▾
        </span>
        <span
          className={`absolute -left-5 text-xs transition-opacity ${direction === "left" ? "opacity-100 scale-125" : "opacity-20"}`}
        >
          ◂
        </span>
        <span
          className={`absolute -right-5 text-xs transition-opacity ${direction === "right" ? "opacity-100 scale-125" : "opacity-20"}`}
        >
          ▸
        </span>
        <span className="text-3xl z-10 drop-shadow-md">◈</span>
      </motion.div>
      <motion.div
        className={`absolute h-0.5 w-full ${vpnOn ? "bg-purple-600 dark:bg-primary" : "bg-cyan-600 dark:bg-secondary"}`}
        initial={{ opacity: 0 }}
        animate={{ opacity: isClosed ? 1 : 0 }}
      />
    </motion.div>
  );
}

function CyberWatcherEyes({ vpnOn }: { vpnOn: boolean }) {
  const [isBlinking, setIsBlinking] = useState(false);
  const [targetCoords, setTargetCoords] = useState({ x: 0, y: 0 });
  const timerRef = useRef<any>(null);
  const lastInteraction = useRef<number>(0);

  // Логика моргания
  useEffect(() => {
    const schedule = () => {
      timerRef.current = setTimeout(
        () => {
          setIsBlinking(true);
          setTimeout(() => {
            setIsBlinking(false);
            schedule();
          }, 140);
        },
        Math.random() * 3500 + 1500,
      );
    };
    if (!vpnOn) schedule();
    return () => clearTimeout(timerRef.current);
  }, [vpnOn]);

  // Логика слежения и случайного блуждания
  useEffect(() => {
    // Изначально смотрим в центр
    setTargetCoords({ x: window.innerWidth / 2, y: window.innerHeight / 2 });

    const handleInteract = (e: MouseEvent | TouchEvent) => {
      lastInteraction.current = Date.now();
      let clientX, clientY;

      if ("touches" in e && e.touches.length > 0) {
        clientX = e.touches[0].clientX;
        clientY = e.touches[0].clientY;
      } else {
        clientX = (e as MouseEvent).clientX;
        clientY = (e as MouseEvent).clientY;
      }

      setTargetCoords({ x: clientX, y: clientY });
    };

    window.addEventListener("mousemove", handleInteract);
    window.addEventListener("touchstart", handleInteract, { passive: true });
    window.addEventListener("pointerdown", handleInteract);

    // Интервал для "живого" взгляда на мобилках
    const randomLookInterval = setInterval(() => {
      const isMobile = window.innerWidth <= 768 || "ontouchstart" in window;

      // Если на мобилке и юзер не трогал экран последние 2.5 секунды
      if (isMobile && Date.now() - lastInteraction.current > 2500) {
        // Выбираем случайную точку, но не слишком близко к краям экрана
        setTargetCoords({
          x:
            window.innerWidth * 0.2 + Math.random() * (window.innerWidth * 0.6),
          y:
            window.innerHeight * 0.2 +
            Math.random() * (window.innerHeight * 0.6),
        });
      }
    }, 2000); // Раз в 2 секунды глаза могут сменить цель

    return () => {
      window.removeEventListener("mousemove", handleInteract);
      window.removeEventListener("touchstart", handleInteract);
      window.removeEventListener("pointerdown", handleInteract);
      clearInterval(randomLookInterval);
    };
  }, []);

  const shouldBeClosed = vpnOn || isBlinking;

  return (
    <div className="flex gap-6 md:gap-10 justify-center mb-12 h-20 items-center select-none pointer-events-none">
      <CyberEye
        isClosed={shouldBeClosed}
        vpnOn={vpnOn}
        targetX={targetCoords.x}
        targetY={targetCoords.y}
      />
      <CyberEye
        isClosed={shouldBeClosed}
        vpnOn={vpnOn}
        targetX={targetCoords.x}
        targetY={targetCoords.y}
      />
    </div>
  );
}

export function Hero({
  dict,
  lang,
}: {
  dict: Dictionary["hero"];
  lang: string;
}) {
  const [isVpnOn, setIsVpnOn] = useState(false);
  const { resolvedTheme } = useTheme();

  return (
    <section className="relative pt-32 pb-20 md:pt-48 md:pb-32 flex flex-col items-center text-center px-4 min-h-[95vh] justify-center overflow-hidden select-none">
      {/* --- RUST BACKGROUND --- */}
      <div className="absolute inset-0 -z-10 bg-background pointer-events-auto">
        <NetrunnerMatrix isSecure={isVpnOn} />
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_transparent_20%,_var(--background)_120%)] opacity-80 pointer-events-none" />
        <div className="absolute inset-x-0 top-0 h-64 bg-gradient-to-b from-background via-transparent to-transparent opacity-90 pointer-events-none" />
      </div>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="relative z-10 w-full max-w-4xl mx-auto pt-40 md:pt-48 pb-20 pointer-events-none"
      >
        <div className="pointer-events-auto flex flex-col items-center">
          <motion.div
            layout
            className={`inline-flex items-center gap-2 px-4 py-1.5 rounded-full border text-sm font-bold mb-8 transition-colors duration-500 shadow-sm cursor-default ${
              isVpnOn
                ? "bg-primary/10 border-primary/50 text-primary"
                : "bg-secondary/10 border-secondary/50 text-secondary"
            }`}
          >
            {isVpnOn ? (
              <Shield className="w-4 h-4" />
            ) : (
              <EyeOff className="w-4 h-4" />
            )}
            <span>{isVpnOn ? dict.badgeSecure : dict.badge}</span>
          </motion.div>

          <CyberWatcherEyes vpnOn={isVpnOn} />

          <h1 className="text-4xl md:text-6xl font-extrabold tracking-tight text-foreground mb-6 font-mono cursor-default">
            {dict.titleStart}{" "}
            <span
              className={`transition-all duration-500 ${
                isVpnOn
                  ? "text-primary drop-shadow-[0_0_15px_rgba(139,61,255,0.4)]"
                  : "text-secondary drop-shadow-[0_0_15px_rgba(0,229,242,0.4)]"
              }`}
            >
              {dict.titleHighlight}
            </span>
          </h1>

          <p className="text-muted-foreground font-medium text-lg md:text-xl max-w-2xl mx-auto mb-12 cursor-default">
            {dict.subtitle}
          </p>

          <div className="flex flex-col items-center gap-8 mb-12">
            <div className="flex items-center gap-4 bg-card/80 backdrop-blur-xl border border-border p-4 rounded-3xl shadow-md transition-colors duration-300">
              <Switch
                checked={isVpnOn}
                onCheckedChange={setIsVpnOn}
                className="data-[state=checked]:bg-primary data-[state=unchecked]:bg-secondary"
              />
              <span
                className={`text-base font-bold font-mono transition-colors ${isVpnOn ? "text-primary" : "text-foreground"}`}
              >
                Netrunner VPN
              </span>
            </div>

            <div className="flex flex-col sm:flex-row gap-6 justify-center w-full sm:w-auto font-mono">
              <CyberButton
                href={`/${lang}/download`}
                variant={isVpnOn ? "primary" : "secondary"}
              >
                {dict.ctaPrimary}
              </CyberButton>
              <CyberButton href={`/${lang}/nodes`} variant="secondary">
                {dict.ctaSecondary}
              </CyberButton>
            </div>
          </div>
        </div>
      </motion.div>
    </section>
  );
}
