import { useEffect } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { useProfileStore } from "../stores/useProfileStore";

export default function Pair() {
  const [params] = useSearchParams();
  const navigate = useNavigate();
  const { setGroupId } = useProfileStore();

  const groupId = params.get("g");

  useEffect(() => {
    if (groupId) {
      setGroupId(groupId);
      const t = setTimeout(() => navigate("/", { replace: true }), 1500);
      return () => clearTimeout(t);
    }
  }, [groupId, setGroupId, navigate]);

  if (!groupId) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="paper-panel px-6 py-5 text-center">
          <div className="text-xs uppercase tracking-[0.22em] text-fail">Invalid</div>
          <p className="mt-2 text-sm text-ink">This pairing link is malformed.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center px-4">
      <div className="paper-panel px-8 py-8 max-w-sm w-full text-center">
        <div className="text-xs uppercase tracking-[0.22em] text-ok">Paired</div>
        <h1 className="font-display text-2xl text-ink mt-2 tracking-tight">
          Device linked
        </h1>
        <p className="text-sm text-ink-muted mt-3 leading-relaxed">
          Your devices will recognize each other automatically from now on.
        </p>
        <p className="text-xs text-ink-faint mt-6 font-mono uppercase tracking-widest">
          Redirecting…
        </p>
      </div>
    </div>
  );
}
