"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useReducedMotion } from "motion/react";
import { ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Container } from "@/components/container";
import { cn } from "@/lib/utils";

const REDIRECT_MS = 7000;

export function ThankYouContent() {
  const reduce = useReducedMotion();
  const router = useRouter();

  const [from, setFrom] = useState<string | null>(null);
  // Reveal is driven by React state + CSS transitions (an effect always fires,
  // even in a throttled/background tab) so content is NEVER left invisible.
  const [shown, setShown] = useState(false);
  const [progress, setProgress] = useState(0);
  const [paused, setPaused] = useState(false);
  const pausedRef = useRef(false);
  useEffect(() => {
    pausedRef.current = paused;
  }, [paused]);

  // useReducedMotion() is null on the server but a real boolean on the client's
  // first render — so gate reduce-dependent markup on mount (`shown`) to keep the
  // first client render identical to the server (no hydration mismatch).
  const effectiveReduce = shown ? !!reduce : false;

  useEffect(() => {
    try {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: reads the ?from query param on mount (client-only, SSR-safe)
      setFrom(new URLSearchParams(window.location.search).get("from"));
    } catch {
      /* ignore */
    }
    // Not rAF (throttled in background tabs) — an effect fires regardless of
    // focus, so content is always revealed.
    setShown(true);
  }, []);

  // Auto-return home with a live progress bar (motion users only; pausable).
  useEffect(() => {
    if (reduce) return;
    let raf = 0;
    let last: number | null = null;
    let elapsed = 0;
    const tick = (t: number) => {
      if (last === null) last = t;
      const dt = Math.min(t - last, 100); // clamp long frames (bg-tab resume)
      last = t;
      if (!pausedRef.current) {
        elapsed += dt;
        const p = Math.min(1, elapsed / REDIRECT_MS);
        setProgress(p);
        if (p >= 1) {
          router.push("/");
          return;
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [reduce, router]);

  const support =
    from === "contact"
      ? "Your message has reached our team. There's nothing more to do — we'll review it and reply from a real person, not a bot."
      : "Your request has been received. There's nothing more you need to submit — our team takes it from here.";

  // Staggered reveal via transition-delay; snaps to visible instantly under reduce.
  const reveal = () =>
    cn(
      "transition-all duration-500 ease-out will-change-[opacity,transform]",
      effectiveReduce || shown ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3",
    );
  const delayStyle = (delay: number) =>
    effectiveReduce ? undefined : { transitionDelay: shown ? `${delay}ms` : "0ms" };

  return (
    <Container className="flex min-h-[70vh] max-w-2xl flex-col items-center justify-center py-20 text-center md:py-28">
      {/* Branded signal mark (not a generic green check) */}
      <div className={reveal()} style={delayStyle(0)}>
        <div className="relative flex size-24 items-center justify-center" aria-hidden>
          {!reduce &&
            [0, 1, 2].map((i) => (
              <span
                key={i}
                className="absolute inset-0 rounded-full border border-foreground/30 motion-safe:animate-ping"
                style={{ animationDuration: "2.6s", animationDelay: `${i * 0.85}s`, opacity: 0.25 }}
              />
            ))}
          <span className="absolute inset-[18%] rounded-full border-2 border-foreground" />
          <span className="relative font-display text-3xl font-bold text-foreground">Q</span>
        </div>
      </div>

      <p
        className={cn("mt-8 text-xs font-bold uppercase tracking-[0.2em] text-muted-foreground", reveal())}
        style={delayStyle(120)}
      >
        MESSAGE RECEIVED
      </p>

      <h1
        className={cn(
          "mt-4 font-display text-3xl font-extrabold tracking-tight text-foreground text-balance sm:text-5xl",
          reveal(),
        )}
        style={delayStyle(200)}
      >
        You&apos;re on the right signal.
      </h1>

      <p
        className={cn(
          "mt-4 max-w-lg text-pretty text-base leading-relaxed text-muted-foreground sm:text-lg",
          reveal(),
        )}
        style={delayStyle(300)}
      >
        {support}
      </p>

      {/* Smart next actions (real routes only) */}
      <div
        className={cn("mt-9 flex flex-col items-center gap-3 sm:flex-row", reveal())}
        style={delayStyle(400)}
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        onFocusCapture={() => setPaused(true)}
        onBlurCapture={() => setPaused(false)}
      >
        <Button asChild variant="brand" size="pill">
          <Link href="/">
            Continue to home
            <ArrowRight className="size-4" />
          </Link>
        </Button>
        <Button asChild variant="outline" size="pill">
          <Link href="/#solutions">Explore solutions</Link>
        </Button>
        <Button asChild variant="outline" size="pill">
          <Link href="/industries">Explore industries</Link>
        </Button>
      </div>

      {/* Auto-return progress (motion users only) */}
      {!effectiveReduce && (
        <div className={cn("mt-10 w-full max-w-xs", reveal())} style={delayStyle(500)}>
          <div className="flex items-center justify-between text-[11px] font-medium text-muted-foreground">
            <span>{paused ? "Auto-return paused" : "Returning you home"}</span>
            <button
              type="button"
              onClick={() => router.push("/")}
              className="cursor-pointer font-semibold text-foreground underline-offset-2 hover:underline focus-visible:outline-none focus-visible:underline"
            >
              Skip →
            </button>
          </div>
          <div className="mt-2 h-1 overflow-hidden rounded-full bg-border">
            <div
              className="h-full rounded-full bg-primary"
              style={{ width: `${Math.round(progress * 100)}%` }}
            />
          </div>
        </div>
      )}
    </Container>
  );
}
