// // app/brands/BrandsClient.tsx // 'use client'; // import React, { useState, useEffect } from 'react'; // type Brand = { // id: string; // name: string; // logo?: string; // dropship: boolean; // }; // export default function BrandsClient({ brands }: { brands: Brand[] }) { // const [search, setSearch] = useState(''); // const [selectedIds, setSelectedIds] = useState([]); // const [toast, setToast] = useState(''); // const [isScrolled, setIsScrolled] = useState(false); // const [showDropshipOnly, setShowDropshipOnly] = useState(false); // useEffect(() => { // const handleScroll = () => { // setIsScrolled(window.scrollY > 10); // }; // window.addEventListener('scroll', handleScroll); // return () => window.removeEventListener('scroll', handleScroll); // }, []); // const filteredBrands = brands.filter((b) => { // const matchesSearch = b.name.toLowerCase().includes(search.toLowerCase()); // const matchesDropship = showDropshipOnly ? b.dropship : true; // return matchesSearch && matchesDropship; // }); // const allFilteredSelected = filteredBrands.length > 0 && filteredBrands.every((b) => selectedIds.includes(b.id)); // const toggleSelect = (id: string) => { // setSelectedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id])); // }; // const toggleSelectAll = () => { // console.log('Toggling select all', filteredBrands); // const ids = filteredBrands.map((b) => b.id); // if (allFilteredSelected) { // setSelectedIds((prev) => prev.filter((id) => !ids.includes(id))); // } else { // setSelectedIds((prev) => Array.from(new Set([...prev, ...ids]))); // } // }; // const getSelectedStatusText = () => { // if (selectedIds.length === 0) return 'No brands selected'; // if (selectedIds.length === 1) return '1 brand selected'; // return `${selectedIds.length} brands selected`; // }; // const USER_ID = '6ac40b29-8c50-4800-9ece-62b44b69019a'; // static user id // const handleSave = async () => { // const payload = { // userid: USER_ID, // brands: brands // .filter((b) => selectedIds.includes(b.id)) // .map((b) => ({ // id: b.id, // name: b.name, // logo: b.logo, // dropship: b.dropship, // })), // }; // try { // const res = await fetch('https://ebay.backend.data4autos.com/api/brands/bulk-insert', { // method: 'POST', // headers: { // 'Content-Type': 'application/json', // }, // body: JSON.stringify(payload), // }); // const data = await res.json(); // console.log('Save response:', data); // // Show beautiful message // setToast(`${data.message} (Code: ${data.code}, User: ${data.userid})`); // setTimeout(() => setToast(''), 4000); // } catch (error) { // console.error('Error saving brands:', error); // setToast('Failed to save collections. Please try again.'); // setTimeout(() => setToast(''), 4000); // } // }; // // Function to generate filter status text // const getFilterStatusText = () => { // if (filteredBrands.length === brands.length && !search && !showDropshipOnly) { // return `Showing all ${brands.length} brands`; // } // let status = `Showing ${filteredBrands.length} of ${brands.length} brands`; // if (search && showDropshipOnly) { // status += ` matching "${search}" and dropship only`; // } else if (search) { // status += ` matching "${search}"`; // } else if (showDropshipOnly) { // status += ` (dropship only)`; // } // return status; // }; // return ( //
// {/* Enhanced Fixed Header */} //
//
//
//
//

Data4Autos Turn14 Brands

//

{getFilterStatusText()}

//

{getSelectedStatusText()}

//
//
//
//
// // // //
// setSearch(e.target.value)} // placeholder="Search brands…" // className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" // /> //
//
// // // //
//
//
//
//
// {/* Brand Grid */} //
// {filteredBrands.length > 0 ? ( //
// {/* {filteredBrands.map((brand, index) => ( */} // {[...filteredBrands] // .sort((a, b) => { // const aSelected = selectedIds.includes(a.id); // const bSelected = selectedIds.includes(b.id); // if (aSelected && !bSelected) return -1; // if (!aSelected && bSelected) return 1; // return 0; // }) // .map((brand, index) => ( //
toggleSelect(brand.id)} // > //
// //
// {brand.dropship && ( //
// Dropship //
// )} //
//
// {brand.name} //
//

{brand.name}

//
//
// ))} //
// ) : ( //
//
// // // //

No brands found

//

Try adjusting your search query or filter settings

//
//
// )} //
// {/* Enhanced Toast Notification */} // {/* {toast && ( //
//
// // // // {toast} //
//
// )} */} // {toast && ( //
//
// // // // {toast} //
//
// )} // {/* Add custom animations */} // //
// ); // } 'use client'; import { getAccessToken_client } from '@/utils/apiHelper_client'; import axios from 'axios'; import { useRouter } from 'next/navigation'; import React, { useState, useEffect } from 'react'; type Brand = { id: string; name: string; logo?: string; dropship: boolean; }; async function fetchBrands(accessToken: string): Promise { const resp = await fetch('https://turn14.data4autos.com/v1/brands', { headers: { Authorization: `Bearer ${accessToken}` }, cache: 'no-store', }); if (!resp.ok) { throw new Error(`Failed to fetch brands: ${resp.statusText}`); } const data = await resp.json(); return data.data || []; } export default function BrandsClient() { const router = useRouter() const [brands, setBrands] = useState([]); const [search, setSearch] = useState(''); const [selectedIds, setSelectedIds] = useState([]); const [toast, setToast] = useState(''); const [isScrolled, setIsScrolled] = useState(false); const [showDropshipOnly, setShowDropshipOnly] = useState(false); const [payment, setPayment] = useState(null); const userId = sessionStorage.getItem('USERID'); 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(() => { const fetchUserBrands = async () => { try { //console.log('Fetching access token...'); // Debugging line const accessToken = await getAccessToken_client(); //console.log('Access Token:', accessToken); // Debugging line const brands = accessToken ? await fetchBrands(accessToken) : []; setBrands(brands); const res = await fetch(`https://ebay.backend.data4autos.com/api/brands/${userId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', // Optionally add Authorization: `Bearer ${accessToken}` if needed }, }); const data = await res.json(); console.log('GET response:', data); // Extract selected brand IDs from the response const userSelectedIds = data.map((b: any) => String(b.brandid)); // brandid from your response setSelectedIds(userSelectedIds); // Optional: show toast setToast(`Loaded ${userSelectedIds.length} selected brands`); setTimeout(() => setToast(''), 4000); } catch (error) { console.error('Error fetching brands:', error); setToast('Failed to load user brands'); setTimeout(() => setToast(''), 4000); } }; fetchUserBrands(); }, []); useEffect(() => { const handleScroll = () => { setIsScrolled(window.scrollY > 10); }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); const filteredBrands = brands.filter((b) => { const matchesSearch = b.name.toLowerCase().includes(search.toLowerCase()); const matchesDropship = showDropshipOnly ? b.dropship : true; return matchesSearch && matchesDropship; }); const allFilteredSelected = filteredBrands.length > 0 && filteredBrands.every((b) => selectedIds.includes(b.id)); const toggleSelect = (id: string) => { setSelectedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id])); }; const toggleSelectAll = () => { const ids = filteredBrands.map((b) => b.id); if (allFilteredSelected) { setSelectedIds((prev) => prev.filter((id) => !ids.includes(id))); } else { setSelectedIds((prev) => Array.from(new Set([...prev, ...ids]))); } }; const getSelectedStatusText = () => { if (selectedIds.length === 0) return 'No brands selected'; if (selectedIds.length === 1) return '1 brand selected'; return `${selectedIds.length} brands selected`; }; //const userId = sessionStorage.getItem('USERID'); // dynamic user id const handleSave = async () => { const payload = { userid: userId, brands: brands .filter((b) => selectedIds.includes(b.id)) .map((b) => ({ id: b.id, name: b.name, logo: b.logo, dropship: b.dropship, })), }; try { const res = await fetch('https://ebay.backend.data4autos.com/api/brands/bulk-insert', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); const data = await res.json(); setToast(`${data.message} (Code: ${data.code}, User: ${data.userid})`); setTimeout(() => setToast(''), 4000); } catch (error) { console.error('Error saving brands:', error); setToast('Failed to save collections. Please try again.'); setTimeout(() => setToast(''), 4000); } }; const getFilterStatusText = () => { if (filteredBrands.length === brands.length && !search && !showDropshipOnly) { return `Showing all ${brands.length} brands`; } let status = `Showing ${filteredBrands.length} of ${brands.length} brands`; if (search && showDropshipOnly) { status += ` matching "${search}" and dropship only`; } else if (search) { status += ` matching "${search}"`; } else if (showDropshipOnly) { status += ` (dropship only)`; } return status; }; return (
{/* Sticky Header (below default Header) */}

Data4Autos Turn14 Brands

{getFilterStatusText()}

{getSelectedStatusText()}

setSearch(e.target.value)} placeholder="Search brands…" className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" />
{/* Brand Grid */}
{filteredBrands.length > 0 ? (
{[...filteredBrands] .sort((a, b) => { const aSelected = selectedIds.includes(a.id); const bSelected = selectedIds.includes(b.id); if (aSelected && !bSelected) return -1; if (!aSelected && bSelected) return 1; return 0; }) .map((brand, index) => (
toggleSelect(brand.id)} >
{brand.dropship && (
Dropship
)}
{brand.name}

{brand.name}

ID : {brand.id}

))}
) : (

No brands found

Try adjusting your search query or filter settings

)}
{/* Toast Notification */} {toast && (
{toast}
)} {/* Custom Animations */}
); }