"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Mail } from "lucide-react";
import { CONTACT_EMAIL } from "../types";

const HANDLE = "getspaced";

// Discord presence via SHSF (drives the avatar ring + name dot colour).
const STATUS_URL =
  "https://shsf.reversed.dev/api/exec/6/c084ec4a-1b20-491e-ab2e-67c5fa8881e6";

type Presence = "online" | "idle" | "dnd" | "offline";

const PRESENCE: Record<Presence, { ring: string; glow: string; dot: string; label: string }> = {
  online: {
    ring: "border-emerald-400/70",
    glow: "bg-emerald-500/30",
    dot: "bg-emerald-400 shadow-[0_0_12px_rgba(52,211,153,0.8)]",
    label: "Online",
  },
  idle: {
    ring: "border-amber-400/70",
    glow: "bg-amber-500/30",
    dot: "bg-amber-400 shadow-[0_0_12px_rgba(251,191,36,0.8)]",
    label: "Idle",
  },
  dnd: {
    ring: "border-red-500/70",
    glow: "bg-red-500/30",
    dot: "bg-red-500 shadow-[0_0_12px_rgba(239,68,68,0.8)]",
    label: "Do Not Disturb",
  },
  offline: {
    ring: "border-gray-500/60",
    glow: "bg-gray-500/20",
    dot: "bg-gray-500",
    label: "Offline",
  },
};

function isPresence(value: unknown): value is Presence {
  return value === "online" || value === "idle" || value === "dnd" || value === "offline";
}

export function Hero() {
  const router = useRouter();
  const [presence, setPresence] = useState<Presence>("offline");

  // Hidden easter egg: rapidly shake the mouse back and forth over the avatar
  // (10 quick direction changes) to jump to the admin panel.
  const lastX = useRef<number | null>(null);
  const lastDir = useRef<"left" | "right" | null>(null);
  const lastTime = useRef<number>(0);
  const shakeCount = useRef<number>(0);
  const resetTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleAvatarMouseMove = (e: React.MouseEvent) => {
    const currentX = e.clientX;
    const currentTime = Date.now();

    if (lastX.current !== null) {
      const deltaX = currentX - lastX.current;
      const velocity = Math.abs(deltaX) / (currentTime - lastTime.current || 1);
      const direction = deltaX > 0 ? "right" : "left";

      if (velocity > 2 && direction !== lastDir.current) {
        shakeCount.current += 1;
        lastDir.current = direction;

        if (shakeCount.current >= 10) {
          shakeCount.current = 0;
          setTimeout(() => router.push("/admin"), 0);
        }

        if (resetTimeout.current) clearTimeout(resetTimeout.current);
        resetTimeout.current = setTimeout(() => {
          shakeCount.current = 0;
        }, 1000);
      }
    }

    lastX.current = currentX;
    lastTime.current = currentTime;
  };

  useEffect(() => {
    let cancelled = false;
    fetch(STATUS_URL)
      .then((r) => r.json())
      .then((d) => {
        if (!cancelled && isPresence(d?.status)) setPresence(d.status);
      })
      .catch(() => {
        /* keep offline on failure */
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const style = PRESENCE[presence];

  return (
    <section className="mx-auto w-full max-w-5xl px-4">
      <div className="flex flex-col-reverse items-center gap-8 sm:flex-row sm:items-start sm:justify-between sm:gap-10">
        {/* Left: identity */}
        <div className="flex-1 space-y-5 text-center sm:text-left">
          <div className="space-y-2">
            <h1 className="flex items-center justify-center gap-3 text-4xl font-extrabold text-white sm:justify-start sm:text-5xl">
              Paul&nbsp;W.
              <span
                className={`inline-block h-3 w-3 rounded-full transition-colors duration-500 ${style.dot}`}
                title={style.label}
                aria-label={style.label}
              />
            </h1>
            <p className="font-mono text-sm text-gray-500">{HANDLE}</p>
          </div>

          <p className="mx-auto max-w-xl text-base leading-relaxed text-gray-400 sm:mx-0 sm:text-lg">
            Full-stack developer &amp; open-source author. Building server
            infrastructure, developer tools, and web applications.
          </p>

          <div className="flex flex-wrap items-center justify-center gap-3 sm:justify-start">
            <a
              href={`mailto:${CONTACT_EMAIL}`}
              className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-5 py-2.5 text-sm font-medium text-gray-200 transition-all duration-300 hover:border-white/25 hover:bg-white/10"
            >
              <Mail className="h-4 w-4" />
              Contact
            </a>

            <a
              href="https://github.com/Space-Banane"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2.5 text-sm font-medium text-gray-200 transition-all duration-300 hover:border-gray-400 hover:bg-white/10"
              aria-label="GitHub"
            >
              <svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
                <path d="M12 2C6.48 2 2 6.48 2 12c0 4.42 2.87 8.17 6.84 9.49.5.09.68-.22.68-.48 0-.24-.01-.87-.01-1.71-2.78.6-3.37-1.34-3.37-1.34-.45-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.61.07-.61 1 .07 1.53 1.03 1.53 1.03.89 1.52 2.34 1.08 2.91.83.09-.65.35-1.08.64-1.33-2.22-.25-4.56-1.11-4.56-4.95 0-1.09.39-1.98 1.03-2.68-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02A9.56 9.56 0 0112 6.8c.85.004 1.71.115 2.51.338 1.91-1.29 2.75-1.02 2.75-1.02.55 1.38.2 2.4.10 2.65.64.7 1.03 1.59 1.03 2.68 0 3.85-2.34 4.7-4.57 4.95.36.31.68.92.68 1.86 0 1.34-.01 2.42-.01 2.75 0 .26.18.58.69.48A10.01 10.01 0 0022 12c0-5.52-4.48-10-10-10z" />
              </svg>
              GitHub
            </a>

            <a
              href="https://gitea.reversed.dev/space"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2.5 text-sm font-medium text-gray-200 transition-all duration-300 hover:border-emerald-400/50 hover:bg-white/10"
              aria-label="Gitea"
            >
              <img
                src="https://gitea.reversed.dev/assets/img/logo.svg"
                alt=""
                className="h-5 w-5"
              />
              Gitea
            </a>
          </div>

          <p className="text-xs uppercase tracking-[0.2em] text-gray-600">
            <span className="text-gray-500">◷</span> Europe/Berlin
          </p>
        </div>

        {/* Right: avatar with live status ring */}
        <div className="relative shrink-0" onMouseMove={handleAvatarMouseMove}>
          <div className={`absolute -inset-1 rounded-full blur-md transition-colors duration-500 ${style.glow}`} />
          <div
            className={`relative h-32 w-32 overflow-hidden rounded-full border-4 bg-black transition-colors duration-500 sm:h-44 sm:w-44 ${style.ring}`}
          >
            <img
              src="/api/profile-image"
              alt="Paul W."
              className="h-full w-full scale-105 object-cover"
            />
          </div>
        </div>
      </div>
    </section>
  );
}
