'use client'; import React, { useEffect, useMemo, useState } from 'react'; import { getAccessToken_client } from '@/utils/apiHelper_client'; import { useRouter } from 'next/navigation'; import axios from 'axios'; type StoreFromAPI = { userid: string; store_name: string; store_description: string; store_url: string; store_url_path: string; store_last_opened_time: string | null; store_last_opened_time_raw: string | null; store_logo_url: string; }; type ApiOk = { code: 'STORE_PRESENT'; message: string; store: StoreFromAPI }; type ApiMiss = { code: 'USER_NOT_FOUND_OR_NO_STORE'; message: string }; type ApiResp = ApiOk | ApiMiss | any; const read = async (r: Response) => r.headers.get('content-type')?.includes('application/json') ? r.json() : r.text(); function safeDateFormat(input?: string | null) { if (!input) return '—'; const d = new Date(input); return isNaN(d.getTime()) ? '—' : d.toLocaleString(); } export default function EbayAuthPage() { const router = useRouter() const [status, setStatus] = useState<'loading' | 'connected' | 'disconnected'>('loading'); const [store, setStore] = useState(null); const [toast, setToast] = useState(''); const [connecting, setConnecting] = useState(false); const [connectingAnother, setConnectingAnother] = useState(false); const [payment, setPayment] = useState(null); const returnUrl = useMemo(() => { if (typeof window === 'undefined') return ''; return `${window.location.origin}${window.location.pathname}`; }, []); useEffect(() => { const role = localStorage.getItem("user_role"); const sessionId = localStorage.getItem("payment_session"); // ✅ Admins and Partners can access directly (skip payment check) if (role === "admin" || role === "partner") { return; } // 🚫 If no payment session, redirect to pricing if (!sessionId) { router.push("/pricing"); return; } // ✅ Otherwise, check payment details const fetchPaymentDetails = async () => { try { const res: any = await axios.get( "https://ebay.backend.data4autos.com/api/payment/details", { params: { session_id: sessionId } } ); setPayment(res.data.payment); } catch (err) { console.error("Error fetching payment details:", err); } }; fetchPaymentDetails(); }, [router]); useEffect(() => { (async () => { try { // await getAccessToken_client().catch(() => null); const userid = sessionStorage.getItem('USERID') || undefined; if (!userid) { setStatus('disconnected'); setToast('No user session found. Please sign in.'); return; } const res = await fetch( 'https://ebay.backend.data4autos.com/api/motorstate/auth/ebay/store/checkstorestatus', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userid }), cache: 'no-store', } ); const data: ApiResp = await read(res); if (data?.code === 'STORE_PRESENT' && data?.store) { setStore(data.store); setStatus('connected'); } else { setStatus('disconnected'); } } catch { setStatus('disconnected'); } })(); }, []); const OAUTH_ENDPOINT = 'https://ebay.backend.data4autos.com/api/ebay/oauth/motorstate/login'; const startOauth = () => { setConnecting(true); const url = `${OAUTH_ENDPOINT}?return_url=${encodeURIComponent(returnUrl)}`; window.location.href = url; }; const startOauthAnother = () => { setConnectingAnother(true); const url = `${OAUTH_ENDPOINT}?return_url=${encodeURIComponent(returnUrl)}&add_another=1`; window.location.href = url; }; const { subtitle, logoUrl, desc, link, lastOpen } = useMemo(() => { if (!store) return { subtitle: '', logoUrl: '', desc: '', link: '', lastOpen: '—' }; return { subtitle: store.store_name || store.store_url_path, logoUrl: store.store_logo_url, desc: store.store_description, link: store.store_url, lastOpen: safeDateFormat(store.store_last_opened_time || store.store_last_opened_time_raw), }; }, [store]); return (
{toast && (
{toast}
)} {status === 'loading' && (
Checking your store status…

Verifying eBay connection…

)} {status === 'connected' && (
✅ Connected

eBay connected successfully! 🎉

{logoUrl ? ( Store Logo ) : (
{(subtitle || 'S').slice(0, 1)}
)}

{subtitle}

Last opened: {lastOpen}

{desc &&

{desc}

}

Use this to link an additional eBay store.

)} {status === 'disconnected' && (

eBay Settings

Connect your eBay store to enable product sync, inventory updates, and order flow.

You’ll be redirected to eBay to authorize access, then returned here.

)}
); }