'use client' import { useState } from 'react' export type PersonalReferralPayload = { refToken: string firstName: string lastName: string email: string password: string phone: string lang?: 'de' | 'en' } export type CompanyReferralPayload = { refToken: string companyEmail: string password: string companyName: string companyPhone: string contactPersonName: string contactPersonPhone: string lang?: 'de' | 'en' } export type GuestReferralPayload = { refToken: string firstName: string lastName: string email: string password: string lang?: 'de' | 'en' } type RegisterResult = { ok: boolean status: number data?: T | null message?: string } function detectLang(): 'de' | 'en' { if (typeof navigator !== 'undefined') { const n = navigator.language || '' if (n.toLowerCase().startsWith('de')) return 'de' } return 'en' } function mapError(status: number): string { switch (status) { case 404: return 'Referral token not found.' case 410: return 'Referral token expired or exhausted.' case 403: return 'Referral token is inactive.' case 400: return 'Invalid registration data or token validation failed.' default: return 'Registration failed. Please try again later.' } } // NEW: read ?ref from the URL as a fallback function getRefTokenFromUrl(): string | null { if (typeof window === 'undefined') return null try { const u = new URL(window.location.href) return u.searchParams.get('ref') } catch { return null } } export function useRegister() { const [loading, setLoading] = useState(false) const [error, setError] = useState('') const base = process.env.NEXT_PUBLIC_API_BASE_URL || '' const registerPersonalReferral = async (payload: PersonalReferralPayload): Promise => { setError('') setLoading(true) // Resolve token: prefer payload, fallback to URL const finalRefToken = (payload.refToken || '').trim() || getRefTokenFromUrl() || '' const body = { ...payload, refToken: finalRefToken, lang: payload.lang || detectLang() } // NOTE: align with other endpoints using /api prefix const url = `${base}/api/register/personal-referral` console.log('🌐 useRegister: POST personal-referral', { url, refToken: finalRefToken ? `${finalRefToken.slice(0, 6)}…${finalRefToken.slice(-6)}` : null }) try { const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const json = await res.json().catch(() => null) console.log('📡 useRegister: personal status:', res.status, 'body:', json) if (!res.ok) { const msg = json?.message || mapError(res.status) setError(msg) return { ok: false, status: res.status, data: json, message: msg } } return { ok: true, status: res.status, data: json, message: json?.message } } catch (e) { console.error('❌ useRegister: personal error:', e) const msg = 'Network error. Please try again later.' setError(msg) return { ok: false, status: 0, data: null, message: msg } } finally { setLoading(false) } } const registerCompanyReferral = async (payload: CompanyReferralPayload): Promise => { setError('') setLoading(true) // Resolve token: prefer payload, fallback to URL const finalRefToken = (payload.refToken || '').trim() || getRefTokenFromUrl() || '' const body = { ...payload, refToken: finalRefToken, lang: payload.lang || detectLang() } // NOTE: align with other endpoints using /api prefix const url = `${base}/api/register/company-referral` console.log('🌐 useRegister: POST company-referral', { url, refToken: finalRefToken ? `${finalRefToken.slice(0, 6)}…${finalRefToken.slice(-6)}` : null }) try { const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const json = await res.json().catch(() => null) console.log('📡 useRegister: company status:', res.status, 'body:', json) if (!res.ok) { const msg = json?.message || mapError(res.status) setError(msg) return { ok: false, status: res.status, data: json, message: msg } } return { ok: true, status: res.status, data: json, message: json?.message } } catch (e) { console.error('❌ useRegister: company error:', e) const msg = 'Network error. Please try again later.' setError(msg) return { ok: false, status: 0, data: null, message: msg } } finally { setLoading(false) } } const registerGuest = async (payload: GuestReferralPayload): Promise => { setError('') setLoading(true) const body = { firstName: payload.firstName, lastName: payload.lastName, email: payload.email, confirmEmail: payload.email, password: payload.password, confirmPassword: payload.password, referralEmail: undefined as string | undefined, lang: payload.lang || detectLang(), } // Try to resolve referral email from token if (payload.refToken) { try { const infoRes = await fetch(`${base}/api/referral/info/${encodeURIComponent(payload.refToken)}`, { method: 'GET', credentials: 'include', }) const infoJson = await infoRes.json().catch(() => null) if (infoJson?.referrerEmail) { body.referralEmail = infoJson.referrerEmail } } catch {} } const url = `${base}/api/register/guest` console.log('🌐 useRegister: POST guest', { url }) try { const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const json = await res.json().catch(() => null) console.log('📡 useRegister: guest status:', res.status, 'body:', json) if (!res.ok) { const msg = json?.message || mapError(res.status) setError(msg) return { ok: false, status: res.status, data: json, message: msg } } return { ok: true, status: res.status, data: json, message: json?.message } } catch (e) { console.error('❌ useRegister: guest error:', e) const msg = 'Network error. Please try again later.' setError(msg) return { ok: false, status: 0, data: null, message: msg } } finally { setLoading(false) } } return { loading, error, setError, registerPersonalReferral, registerCompanyReferral, registerGuest, } }