"use client"; import { useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import Link from "next/link"; import { AlertCircle, Check, Copy, Loader2 } from "lucide-react"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Skeleton } from "@/components/ui/skeleton"; import { Textarea } from "@/components/ui/textarea"; import { useSession } from "@/lib/auth-client"; import { useCopyText } from "@/lib/copy-text"; import { appStoreRedeemUrl } from "@/lib/site"; const APPLY_PATH = "/settings/creator-program"; const PLATFORMS = ["tiktok", "youtube", "instagram", "x", "other"] as const; const AUDIENCE_SIZES = ["under-1k", "1k-10k", "10k-100k", "100k-plus"] as const; const TERM_KEYS = ["termSponsored", "termAds", "termOwn", "termEnd"] as const; const AUDIENCE_KEYS = { "under-1k": "under1k", "1k-10k": "from1k", "10k-100k": "from10k", "100k-plus": "from100k", } as const; interface Application { slug: string | null; status: "pending" | "approved" | "declined" | "revoked"; decline_reason: string | null; app_store_code_added_at: string | null; } type SlugState = { state: "idle" | "checking" } | { state: "available" } | { state: "unavailable"; reason: string }; function CopyField({ label, value, copyLabel }: { label: string; value: string; copyLabel: string }) { const copyText = useCopyText(); const valueRef = useRef(null); const [copied, setCopied] = useState(false); const copy = async () => { const outcome = await copyText(value, valueRef.current); if (outcome !== "copied") { setCopied(false); return; } setCopied(true); setTimeout(() => setCopied(false), 2000); }; return (

{label}

{value}
); } export default function CreatorProgramPage() { const t = useTranslations("settings"); const { data: session, isPending } = useSession(); const [application, setApplication] = useState(null); const [canApplyAt, setCanApplyAt] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [slug, setSlug] = useState(""); const [slugState, setSlugState] = useState({ state: "idle" }); const [platform, setPlatform] = useState(""); const [profileUrl, setProfileUrl] = useState(""); const [audienceSize, setAudienceSize] = useState(""); const [videoUrl, setVideoUrl] = useState(""); const [promotionPlan, setPromotionPlan] = useState(""); const [acceptTerms, setAcceptTerms] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { if (!session?.user?.id) return; fetch("/api/affiliates", { cache: "no-store" }) .then(async (response) => { if (!response.ok) throw new Error(t("creator.loadFailed")); const data = await response.json(); setApplication(data.application); setCanApplyAt(data.can_apply_at); }) .catch((err) => setError(err instanceof Error ? err.message : t("creator.loadFailed"))) .finally(() => setIsLoading(false)); }, [session?.user?.id, t]); useEffect(() => { const value = slug.trim(); if (!value) { setSlugState({ state: "idle" }); return; } setSlugState({ state: "checking" }); const controller = new AbortController(); const timer = setTimeout(async () => { try { const response = await fetch(`/api/affiliates/slug?slug=${encodeURIComponent(value)}`, { signal: controller.signal }); const data = await response.json(); setSlugState(data.available ? { state: "available" } : { state: "unavailable", reason: data.reason || t("creator.notAvailable") }); } catch { if (!controller.signal.aborted) setSlugState({ state: "idle" }); } }, 400); return () => { clearTimeout(timer); controller.abort(); }; }, [slug, t]); const submit = async (event: React.FormEvent) => { event.preventDefault(); setIsSubmitting(true); setError(null); try { const response = await fetch("/api/affiliates", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ slug, platform, profile_url: profileUrl, audience_size: audienceSize, video_url: videoUrl, promotion_plan: promotionPlan, accept_terms: acceptTerms, }), }); const data = await response.json().catch(() => ({})); if (!response.ok) throw new Error(data.error || t("creator.submitFailed")); setApplication(data.application); setCanApplyAt(null); } catch (err) { setError(err instanceof Error ? err.message : t("creator.submitFailed")); } finally { setIsSubmitting(false); } }; if (isPending || (session?.user && isLoading)) { return (
); } if (!session?.user) { return (

{t("creator.signIn")}

); } const canApply = canApplyAt !== null && new Date(canApplyAt).getTime() <= Date.now(); const origin = typeof window === "undefined" ? "" : window.location.origin; const canSubmit = slugState.state === "available" && platform && profileUrl.trim() && audienceSize && acceptTerms && !isSubmitting; return (

{t("creator.title")}

{t.rich("creator.intro", { em: (chunks) => {chunks}, })}{" "} {t("creator.howItWorks")}

{error && ( {error} )} {application?.status === "approved" && application.slug && (

{t("creator.approvedTitle")}

{t("creator.approvedBadge")}

{t("creator.approvedBody")}

{application.app_store_code_added_at ? ( ) : (

{t("creator.iphonePending")}

)}
)} {application?.status === "pending" && (

{t("creator.pendingTitle")}

{t("creator.pendingBadge")}

{t.rich("creator.pendingBody", { code: application.slug?.toUpperCase() ?? "", mono: (chunks) => {chunks}, })}

)} {application?.status === "revoked" && (

{t("creator.revokedTitle")}

{t("creator.revokedBody")}

)} {application?.status === "declined" && !canApply && (

{t("creator.declinedTitle")}

{application.decline_reason &&

{application.decline_reason}

} {canApplyAt && (

{t("creator.applyAgain", { date: new Date(canApplyAt).toLocaleDateString() })}

)}
)} {canApply && (
setSlug(event.target.value.replace(/\s+/g, ""))} placeholder={t("creator.codePlaceholder")} maxLength={20} autoComplete="off" className="mt-1.5 font-mono" />

{slugState.state === "checking" && <> {t("creator.checking")}} {slugState.state === "available" && ( {t("creator.available", { origin, slug: slug.trim().toLowerCase(), code: slug.trim().toUpperCase() })} )} {slugState.state === "unavailable" && {slugState.reason}} {slugState.state === "idle" && t("creator.codeHint")}

setProfileUrl(event.target.value)} placeholder={t("creator.profilePlaceholder")} className="mt-1.5" />
setVideoUrl(event.target.value)} placeholder={t("creator.videoPlaceholder")} className="mt-1.5" />