import { useEffect, useMemo, useState } from "react";
import PageMeta from "../../components/common/PageMeta";
import AuthLayout from "./AuthPageLayout";
import SignUpForm from "../../components/auth/SignUpForm";

export default function SignUp() {
  const planSlug = useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("plan") || "";
  }, []);

  const [planDetails, setPlanDetails] = useState<any | null>(null);
  const [planLoading, setPlanLoading] = useState(false);

  useEffect(() => {
    const fetchPlans = async () => {
      if (!planSlug) return;
      setPlanLoading(true);
      try {
        const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || "https://api.igny8.com/api";
        const res = await fetch(`${API_BASE_URL}/v1/auth/plans/`);
        const data = await res.json();
        const plans = data?.results || [];
        const plan = plans.find((p: any) => p.slug === planSlug);
        if (plan) {
          const features = Array.isArray(plan.features)
            ? plan.features.map((f: string) => f.charAt(0).toUpperCase() + f.slice(1))
            : [];
          setPlanDetails({ ...plan, features });
        }
      } catch (e) {
        // ignore; SignUpForm will handle lack of plan data gracefully
      } finally {
        setPlanLoading(false);
      }
    };
    fetchPlans();
  }, [planSlug]);

  return (
    <>
      <PageMeta
        title="React.js SignUp Dashboard | TailAdmin - Next.js Admin Dashboard Template"
        description="This is React.js SignUp Tables Dashboard page for TailAdmin - React.js Tailwind CSS Admin Dashboard Template"
      />
      <AuthLayout plan={planDetails}>
        <SignUpForm planDetails={planDetails} planLoading={planLoading} />
      </AuthLayout>
    </>
  );
}
