"use client";

import { useMemo, useState, useEffect } from "react";
import Link from "next/link";
import LoginCheckboxActiveSvg from "@/app/svgs/logincheckboxactivesvg";
import LoginCheckboxInactiveSvg from "@/app/svgs/logincheckboxinactivesvg";
import LoginInputSvg from "@/app/svgs/inputformx";
import CalendarSvg from "@/app/svgs/callendar";
import apiService from "@/app/lib/apiService";

type Gender = "MALE" | "FEMALE" | "";

type RegisterFormProps = {
	onOpenDone: () => void;
	onOpenCodeError: (message?: string) => void;
};

export default function RegisterForm({ onOpenDone, onOpenCodeError }: RegisterFormProps) {
	const [name, setName] = useState("");
	const [phone, setPhone] = useState("");
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [passwordConfirm, setPasswordConfirm] = useState("");
	const [gender, setGender] = useState<Gender>("");
	const [birthdate, setBirthdate] = useState("");
	const [birthdateInput, setBirthdateInput] = useState("");

	// 이메일 인증 관련
	const [emailCodeSent, setEmailCodeSent] = useState(false);
	const [emailCode, setEmailCode] = useState("");
	const [emailCodeVerified, setEmailCodeVerified] = useState(false);

	const [agreeAge, setAgreeAge] = useState(false);
	const [agreeTos, setAgreeTos] = useState(false);
	const [agreePrivacy, setAgreePrivacy] = useState(false);

	const allAgree = useMemo(() => agreeAge && agreeTos && agreePrivacy, [agreeAge, agreeTos, agreePrivacy]);
	function toggleAllAgree(checked: boolean) {
		setAgreeAge(checked);
		setAgreeTos(checked);
		setAgreePrivacy(checked);
	}

	const [focused, setFocused] = useState<Record<string, boolean>>({});
	const [errors, setErrors] = useState<Record<string, string>>({});

	// 휴대폰 번호 포맷팅 함수
	function formatPhoneNumber(phoneNumber: string): string {
		const numbers = phoneNumber.replace(/[^0-9]/g, "");
		if (numbers.length <= 3) return numbers;
		if (numbers.length <= 7) return `${numbers.slice(0, 3)}-${numbers.slice(3)}`;
		if (numbers.length <= 11) return `${numbers.slice(0, 3)}-${numbers.slice(3, 7)}-${numbers.slice(7)}`;
		return `${numbers.slice(0, 3)}-${numbers.slice(3, 7)}-${numbers.slice(7, 11)}`;
	}

	// 생년월일 YYYYMMDD를 YYYY-MM-DD로 변환하는 함수
	function parseBirthdate(input: string): string {
		// 숫자만 추출
		const numbers = input.replace(/[^0-9]/g, "");

		// YYYYMMDD 형식인지 확인 (8자리)
		if (numbers.length === 8) {
			const year = numbers.slice(0, 4);
			const month = numbers.slice(4, 6);
			const day = numbers.slice(6, 8);

			// 유효한 날짜인지 검증
			const yearNum = parseInt(year, 10);
			const monthNum = parseInt(month, 10);
			const dayNum = parseInt(day, 10);

			if (yearNum >= 1900 && yearNum <= 2100 && monthNum >= 1 && monthNum <= 12 && dayNum >= 1 && dayNum <= 31) {
				// 날짜 유효성 검사
				const date = new Date(yearNum, monthNum - 1, dayNum);
				if (date.getFullYear() === yearNum && date.getMonth() === monthNum - 1 && date.getDate() === dayNum) {
					return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
				}
			}
		}

		// YYYY-MM-DD 형식이면 그대로 반환
		if (/^\d{4}-\d{2}-\d{2}$/.test(input)) {
			return input;
		}

		return "";
	}

	const isEmailValid = useMemo(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email), [email]);
	const isPhoneValid = useMemo(() => /^\d{9,11}$/.test(phone), [phone]);
	const isPasswordValid = useMemo(() => {
		if (password.length < 8 || password.length > 16) return false;
		const hasEnglish = /[a-zA-Z]/.test(password);
		const hasNumber = /[0-9]/.test(password);
		const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
		return hasEnglish && hasNumber && hasSpecialChar;
	}, [password]);
	const isPasswordConfirmValid = useMemo(() => passwordConfirm === password && passwordConfirm.length > 0, [password, passwordConfirm]);

	const canSubmit = useMemo(() => {
		return (
			name.trim().length > 0 &&
			isPhoneValid &&
			isEmailValid &&
			isPasswordValid &&
			isPasswordConfirmValid &&
			gender !== "" &&
			birthdate.trim().length > 0 &&
			allAgree
		);
	}, [name, isPhoneValid, isEmailValid, isPasswordValid, isPasswordConfirmValid, gender, birthdate, allAgree]);

	function validateAll() {
		const nextErrors: Record<string, string> = {};
		if (name.trim().length === 0) nextErrors.name = "이름을 입력해 주세요.";
		if (!isPhoneValid) nextErrors.phone = "휴대폰 번호를 숫자만 9~11자리로 입력해 주세요.";
		if (!isEmailValid) nextErrors.email = "올바른 이메일 형식을 입력해 주세요.";
		if (!isPasswordValid) {
			if (password.length < 8 || password.length > 16) {
				nextErrors.password = "비밀번호는 8~16자여야 합니다.";
			} else {
				const hasEnglish = /[a-zA-Z]/.test(password);
				const hasNumber = /[0-9]/.test(password);
				const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
				if (!hasEnglish || !hasNumber || !hasSpecialChar) {
					nextErrors.password = "8~16자의 영문/숫자/특수문자를 조합해서 입력해 주세요.";
				}
			}
		}
		if (!isPasswordConfirmValid) nextErrors.passwordConfirm = "비밀번호가 일치하지 않습니다.";
		if (gender === "") nextErrors.gender = "성별을 선택해 주세요.";
		if (birthdate.trim().length === 0) nextErrors.birthdate = "생년월일을 선택해 주세요.";
		if (!allAgree) nextErrors.agreements = "필수 약관에 모두 동의해 주세요.";
		setErrors(nextErrors);
		return Object.keys(nextErrors).length === 0;
	}

	// 입력 필드가 유효해지면 해당 필드의 에러를 자동으로 지움
	useEffect(() => {
		setErrors((prev) => {
			const next = { ...prev };
			if (name.trim().length > 0 && prev.name) delete next.name;
			if (isPhoneValid && prev.phone) delete next.phone;
			if (isEmailValid && prev.email) delete next.email;
			if (isPasswordValid && prev.password) delete next.password;
			if (isPasswordConfirmValid && prev.passwordConfirm) delete next.passwordConfirm;
			if (gender !== "" && prev.gender) delete next.gender;
			if (birthdate.trim().length > 0 && prev.birthdate) delete next.birthdate;
			if (allAgree && prev.agreements) delete next.agreements;
			return next;
		});
	}, [name, isPhoneValid, isEmailValid, isPasswordValid, isPasswordConfirmValid, gender, birthdate, allAgree]);

	async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
		console.log("handleSubmit");
		e.preventDefault();
		if (!validateAll()) return;
		await RegisterUser();
	}

	async function verifyEmailCode() {
		try {
			await apiService.verifyEmailCode(email, emailCode);
			// 인증 성공 시 상태 업데이트
			setEmailCodeVerified(true);
		}
		catch (error) {
			console.error("이메일 인증번호 검증 오류:", error);
			onOpenCodeError();
		}
	}


	async function sendEmailCode() {

		if (!isEmailValid) return;
		try {
			await apiService.sendEmailVerification(email);
			// 성공 시에만 상태 업데이트
			setEmailCodeSent(true);
			setEmailCode("");
			setEmailCodeVerified(false);
			// 성공 시 이메일 에러 제거
			setErrors((prev) => {
				const next = { ...prev };
				if (next.email) delete next.email;
				return next;
			});
		} catch (error) {
			console.error("이메일 인증번호 전송 오류:", error);
			if (error instanceof Error && error.message.includes("409")) {
				setErrors((prev) => ({ ...prev, email: "이메일이 중복되었습니다." }));
			} else {
				alert("인증번호 전송실패");
			}
		}
	}

	async function RegisterUser() {
		if (!emailCodeVerified) {
			onOpenCodeError("이메일 인증을 완료해주세요.");
			return false;
		}
		if (gender === "") {
			onOpenCodeError("성별을 선택해주세요.");
			return false;
		}
		try {
			await apiService.register({
				email,
				emailCode,
				password,
				passwordConfirm,
				name,
				phone,
				gender: gender as "MALE" | "FEMALE",
				birthDate: birthdate
			});
			onOpenDone();
			return true;
		} catch (error) {
			const errorMessage = error instanceof Error ? error.message : "네트워크 오류가 발생했습니다.";
			console.error("회원가입 오류:", errorMessage);
			onOpenCodeError(errorMessage);
			return false;
		}
	}

	return (
		<div className="rounded-xl bg-white max-w-[560px] px-[40px] w-full">
			{/* 로고 / 제목 영역 */}
			<div className="my-15 flex flex-col items-center">
				<div className="text-[24px] font-extrabold leading-[150%] text-neutral-700">
					회원가입
				</div>
			</div>
			<form onSubmit={handleSubmit} className="space-y-6">
				{/* 이름 */}
				<div className="space-y-2">
					<label htmlFor="name" className="text-[15px] font-semibold text-[#6c7682]">이름</label>
					<div className="relative">
						<input
							id="name"
							name="name"
							value={name}
							onChange={(e) => setName(e.target.value)}
							onFocus={() => setFocused((p) => ({ ...p, name: true }))}
							onBlur={() => setFocused((p) => ({ ...p, name: false }))}
							placeholder="이름을 입력해 주세요."
							className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] ${errors.name ? 'border-error' : 'border-neutral-40 focus:border-neutral-700'}`}
						/>
						{name.trim().length > 0 && focused.name && (
							<button
								type="button"
								onMouseDown={(e) => { e.preventDefault(); setName(""); }}
								aria-label="입력 지우기"
								className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
							>
								<LoginInputSvg />
							</button>
						)}
					</div>
					{errors.name && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.name}</p>}
				</div>

				{/* 휴대폰 번호 */}
				<div className="space-y-2">
					<label htmlFor="phone" className="text-[15px] font-semibold text-[#6c7682]">휴대폰 번호</label>
					<div className="relative">
						<input
							id="phone"
							name="phone"
							type="tel"
							inputMode="numeric"
							value={formatPhoneNumber(phone)}
							placeholder="-없이 입력해 주세요."
							onChange={(e) => setPhone(e.target.value.replace(/[^0-9]/g, ""))}
							onFocus={() => setFocused((p) => ({ ...p, phone: true }))}
							onBlur={() => setFocused((p) => ({ ...p, phone: false }))}
							className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] ${errors.phone ? 'border-error' : 'border-neutral-40 focus:border-neutral-700'}`}
						/>
						{phone.trim().length > 0 && focused.phone && (
							<button
								type="button"
								onMouseDown={(e) => { e.preventDefault(); setPhone(""); }}
								aria-label="입력 지우기"
								className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
							>
								<LoginInputSvg />
							</button>
						)}
					</div>
					{errors.phone && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.phone}</p>}
				</div>

				{/* 아이디(이메일) + 인증번호 전송 */}
				<div className="space-y-2">
					<label htmlFor="email" className="text-[15px] font-semibold text-[#6c7682]">아이디 (이메일)</label>
					<div className="flex gap-2 items-center">
						<div className="relative flex-1">
							<input
								id="email"
								name="email"
								type="email"
								value={email}
								onChange={(e) => {
									setEmail(e.target.value);
									// 이메일 변경 시 중복 오류 제거
									if (errors.email === "이메일이 중복되었습니다.") {
										setErrors((prev) => {
											const next = { ...prev };
											delete next.email;
											return next;
										});
									}
								}}
								onFocus={() => setFocused((p) => ({ ...p, email: true }))}
								onBlur={() => setFocused((p) => ({ ...p, email: false }))}
								placeholder="이메일을 입력해 주세요."
								disabled={emailCodeVerified}
								className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] disabled:bg-gray-100 disabled:cursor-not-allowed ${emailCodeVerified ? '' : (errors.email ? 'border-error' : 'border-neutral-40 focus:border-neutral-700')}`}
							/>
							{email.trim().length > 0 && focused.email && !emailCodeVerified && (
								<button
									type="button"
									onMouseDown={(e) => { e.preventDefault(); setEmail(""); }}
									aria-label="입력 지우기"
									className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
								>
									<LoginInputSvg />
								</button>
							)}
						</div>
						<button
							type="button"
							disabled={!isEmailValid || emailCodeVerified}
							className={`h-[40px] w-[130px] px-[12px] rounded-[8px] text-[16px] font-semibold ${isEmailValid && !emailCodeVerified ? "bg-[#F1F3F5] text-neutral-700" : "bg-gray-50 text-input-placeholder-text"}`}
							onClick={sendEmailCode}
						>
							{emailCodeSent && !emailCodeVerified ? "인증번호 재전송" : "인증번호 전송"}
						</button>
					</div>
					{errors.email && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.email}</p>}
					{emailCodeSent && (
						<div className="space-y-2" aria-expanded={emailCodeSent}>
							<label htmlFor="emailCode" className="sr-only">인증번호</label>
							<div className="flex gap-2 items-center">
								<div className="relative flex-1">
									<input
										id="emailCode"
										name="emailCode"
										inputMode="numeric"
										value={emailCode}
										onChange={(e) => {
											const onlyDigits = e.target.value.replace(/[^0-9]/g, "");
											setEmailCode(onlyDigits.slice(0, 6));
										}}
										onFocus={() => setFocused((p) => ({ ...p, emailCode: true }))}
										onBlur={() => setFocused((p) => ({ ...p, emailCode: false }))}
										placeholder="인증번호 6자리"
										disabled={emailCodeVerified}
										className="h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border border-neutral-40 focus:outline-none focus:border-neutral-700 text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] disabled:bg-gray-100 disabled:cursor-not-allowed"
									/>
									{emailCode.trim().length > 0 && focused.emailCode && !emailCodeVerified && (
										<button
											type="button"
											onMouseDown={(e) => { e.preventDefault(); setEmailCode(""); }}
											aria-label="입력 지우기"
											className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
										>
											<LoginInputSvg />
										</button>
									)}
								</div>
								<button
									type="button"
									disabled={emailCodeVerified}
									className={`h-[40px] w-[130px] px-[12px] rounded-[8px] text-[16px] font-semibold ${!emailCodeVerified ? "bg-[#F1F3F5] text-neutral-700" : "bg-gray-50 text-input-placeholder-text"}`}
									onClick={verifyEmailCode}
								>
									{emailCodeVerified ? "인증완료" : "인증하기"}
								</button>
							</div>
							<p className="text-[13px] leading-[normal] text-[#384fbf]">
								{emailCodeVerified ? (
									"인증이 완료됐습니다"
								) : (
									<>
										인증 확인을 위해 작성한 이메일로 인증번호를 발송했습니다.
										<br />
										이메일을 확인해 주세요.
									</>
								)}
							</p>
						</div>
					)}
				</div>

				{/* 비밀번호 */}
				<div className="space-y-2">
					<label htmlFor="password" className="text-[15px] font-semibold text-[#6c7682]">비밀번호</label>
					<div className="relative">
						<input
							id="password"
							name="password"
							type="password"
							value={password}
							onChange={(e) => setPassword(e.target.value)}
							onFocus={() => setFocused((p) => ({ ...p, password: true }))}
							onBlur={() => setFocused((p) => ({ ...p, password: false }))}
							placeholder="8~16자의 영문/숫자/특수문자를 조합해서 입력해 주세요."
							className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] ${errors.password ? 'border-error' : 'border-neutral-40 focus:border-neutral-700'}`}
						/>
						{password.trim().length > 0 && focused.password && (
							<button
								type="button"
								onMouseDown={(e) => { e.preventDefault(); setPassword(""); }}
								aria-label="입력 지우기"
								className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
							>
								<LoginInputSvg />
							</button>
						)}
					</div>
					{errors.password && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.password}</p>}
				</div>

				{/* 비밀번호 확인 */}
				<div className="space-y-2">
					<label htmlFor="passwordConfirm" className="text-[15px] font-semibold text-[#6c7682]">비밀번호 확인</label>
					<div className="relative">
						<input
							id="passwordConfirm"
							name="passwordConfirm"
							type="password"
							value={passwordConfirm}
							onChange={(e) => setPasswordConfirm(e.target.value)}
							onFocus={() => setFocused((p) => ({ ...p, passwordConfirm: true }))}
							onBlur={() => setFocused((p) => ({ ...p, passwordConfirm: false }))}
							placeholder="비밀번호를 다시 입력해 주세요."
							className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] ${errors.passwordConfirm ? 'border-error' : 'border-neutral-40 focus:border-neutral-700'}`}
						/>
						{passwordConfirm.trim().length > 0 && focused.passwordConfirm && (
							<button
								type="button"
								onMouseDown={(e) => { e.preventDefault(); setPasswordConfirm(""); }}
								aria-label="입력 지우기"
								className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
							>
								<LoginInputSvg />
							</button>
						)}
					</div>
					{errors.passwordConfirm && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.passwordConfirm}</p>}
				</div>

				{/* 성별 */}
				<div className="space-y-2">
					<div className="text-[15px] font-semibold text-[#6c7682]">성별</div>
					<div className="flex items-center gap-5 h-[40px]">
						<label className="flex items-center gap-2 cursor-pointer select-none text-[15px] text-neutral-700">
							<input
								type="radio"
								name="gender"
								value="MALE"
								checked={gender === "MALE"}
								onChange={() => setGender("MALE")}
								className="sr-only"
							/>
							<span className={`relative inline-flex items-center justify-center rounded-full w-[18px] h-[18px] shrink-0 border box-border ${gender === "MALE" ? "border-active-button" : "border-[#8c95a1]"}`}>
								{gender === "MALE" && <span className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 block size-[9px] rounded-full bg-active-button" />}
							</span>
							남성
						</label>
						<label className="flex items-center gap-2 cursor-pointer select-none text-[15px] text-neutral-700">
							<input
								type="radio"
								name="gender"
								value="FEMALE"
								checked={gender === "FEMALE"}
								onChange={() => setGender("FEMALE")}
								className="sr-only"
							/>
							<span className={`relative inline-flex items-center justify-center rounded-full w-[18px] h-[18px] shrink-0 border box-border ${gender === "FEMALE" ? "border-active-button" : "border-[#8c95a1]"}`}>
								{gender === "FEMALE" && <span className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 block size-[9px] rounded-full bg-active-button" />}
							</span>
							여성
						</label>
					</div>
					{errors.gender && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.gender}</p>}
				</div>

				{/* 생년월일 */}
				<div className="space-y-2">
					<label htmlFor="birthdate" className="text-[15px] font-semibold text-[#6c7682]">생년월일</label>
					<div className="relative">
						<input
							id="birthdate"
							name="birthdate"
							type="text"
							value={birthdateInput || (birthdate ? birthdate.replace(/-/g, ".") : "")}
							onChange={(e) => {
								const inputValue = e.target.value;
								setBirthdateInput(inputValue);
								if (inputValue === "") {
									setBirthdate("");
								}
							}}
							onBlur={(e) => {
								// 포커스를 잃을 때 YYYYMMDD 형식이면 변환
								const formatted = parseBirthdate(e.target.value);
								if (formatted) {
									setBirthdate(formatted);
									setBirthdateInput("");
								} else if (e.target.value === "") {
									setBirthdate("");
									setBirthdateInput("");
								}
							}}
							placeholder="생년월일"
							className={`h-[40px] px-[12px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] flex items-center ${errors.birthdate ? 'border-error' : 'border-neutral-40 focus:border-neutral-700'}`}
						/>
						<button
							type="button"
							onClick={(e) => {
								e.preventDefault();
								const dateInput = document.getElementById("birthdate-date-picker") as HTMLInputElement;
								dateInput?.showPicker?.();
							}}
							className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
							aria-label="날짜 선택"
						>
							<CalendarSvg width="20" height="20" />
						</button>
						<input
							id="birthdate-date-picker"
							type="date"
							value={birthdate}
							onChange={(e) => {
								setBirthdate(e.target.value);
								setBirthdateInput("");
							}}
							className="absolute right-50 top-1 h-full w-[20px] opacity-0 cursor-pointer"
						/>
					</div>
					{errors.birthdate && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.birthdate}</p>}
				</div>

				{/* 약관 동의 */}
				<div className="space-y-4">
					<label className="flex items-center gap-2 cursor-pointer select-none text-[18px] font-semibold text-neutral-700">
						<input
							type="checkbox"
							checked={allAgree}
							onChange={(e) => toggleAllAgree(e.target.checked)}
							className="sr-only"
						/>
						{allAgree ? <LoginCheckboxActiveSvg /> : <LoginCheckboxInactiveSvg />}
						모든 항목에 동의합니다.
					</label>
					<hr className="h-px bg-input-border border-0" />
					<div className="space-y-3">
						<label className="flex items-center justify-between">
							<span className="flex items-center gap-2 text-[15px] text-neutral-700">
								<input
									type="checkbox"
									checked={agreeAge}
									onChange={(e) => setAgreeAge(e.target.checked)}
									className="sr-only"
								/>
								{agreeAge ? <LoginCheckboxActiveSvg /> : <LoginCheckboxInactiveSvg />}
								<span>만 14세 이상입니다. <span className="text-[#384fbf]">(필수)</span></span>
							</span>
						</label>
						<label className="flex items-center justify-between">
							<span className="flex items-center gap-2 text-[15px] text-neutral-700">
								<input
									type="checkbox"
									checked={agreeTos}
									onChange={(e) => setAgreeTos(e.target.checked)}
									className="sr-only"
								/>
								{agreeTos ? <LoginCheckboxActiveSvg /> : <LoginCheckboxInactiveSvg />}
								<span>이용 약관 동의 <span className="text-[#384fbf]">(필수)</span></span>
							</span>
						</label>
						<label className="flex items-center justify-between">
							<span className="flex items-center gap-2 text-[15px] text-neutral-700">
								<input
									type="checkbox"
									checked={agreePrivacy}
									onChange={(e) => setAgreePrivacy(e.target.checked)}
									className="sr-only"
								/>
								{agreePrivacy ? <LoginCheckboxActiveSvg /> : <LoginCheckboxInactiveSvg />}
								<span>개인정보 수집 및 이용 동의 <span className="text-[#384fbf]">(필수)</span></span>
							</span>
						</label>
					</div>
					{errors.agreements && <p className="text-error text-[13px] leading-tight mt-[10px]">{errors.agreements}</p>}
				</div>

				{/* 액션 버튼 */}
				<div className="flex gap-3 pt-[60px]">
					<Link
						href="/login"
						className="h-[40px] flex-1 rounded-[12px] bg-[#f1f3f5] text-[18px] font-semibold text-center flex items-center justify-center text-basic-text"
					>
						돌아가기
					</Link>
					<button
						type="submit"
						className={`h-[40px] flex-1 rounded-[12px] text-[18px] font-semibold text-center flex items-center justify-center text-white ${canSubmit ? "bg-active-button" : "bg-inactive-button"} cursor-pointer`}
					>
						회원 가입 완료
					</button>
				</div>
			</form>
		</div>
	);
}

