import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { joinCampaign } from "../api";
import styles from "./JoinPage.module.css";

export default function JoinPage() {
  const { token } = useParams<{ token: string }>();
  const navigate = useNavigate();
  const [status, setStatus] = useState<"joining" | "error">("joining");
  const [error, setError] = useState("");

  useEffect(() => {
    if (!token) return;
    joinCampaign(token)
      .then(({ campaignId }) => {
        navigate(`/campaign/${campaignId}`);
      })
      .catch((err) => {
        setStatus("error");
        setError(err instanceof Error ? err.message : "Invalid invite link");
      });
  }, [token, navigate]);

  return (
    <div className={styles.page}>
      <div className={styles.card}>
        {status === "joining" && <div className={styles.title}>Joining campaign…</div>}
        {status === "error" && (
          <>
            <div className={styles.title}>Invalid Invite</div>
            <div className={styles.error}>{error}</div>
          </>
        )}
      </div>
    </div>
  );
}
