78 Commits

Author SHA1 Message Date
f5bdcdd234 Update src/components/sections/product/ProductCardOneWithSaving.tsx 2026-03-11 19:57:04 +00:00
e96e06a541 Update src/components/sections/pricing/PricingCardOneWithSaving.tsx 2026-03-11 19:57:03 +00:00
59b51e581d Update src/components/sections/feature/FeatureCardTwentyFiveWithSaving.tsx 2026-03-11 19:57:03 +00:00
bb62b2d351 Update src/app/page.tsx 2026-03-11 19:57:02 +00:00
02d210a684 Update src/lib/storage/workoutStorage.ts 2026-03-11 19:54:58 +00:00
2b040b39b7 Add src/hooks/useWorkoutStorage.ts 2026-03-11 19:54:57 +00:00
e05a1e869a Add src/components/sections/product/ProductCardOneWithSaving.tsx 2026-03-11 19:54:57 +00:00
3649146e1e Add src/components/sections/pricing/PricingCardOneWithSaving.tsx 2026-03-11 19:54:56 +00:00
c79bc5cf3c Add src/components/sections/metrics/MetricCardFourteenWithSaving.tsx 2026-03-11 19:54:55 +00:00
d328e3221c Add src/components/sections/feature/FeatureCardTwentyFiveWithSaving.tsx 2026-03-11 19:54:55 +00:00
531b1c297b Update src/app/signup/page.tsx 2026-03-11 19:54:54 +00:00
8ae1f717a3 Update src/app/page.tsx 2026-03-11 19:54:53 +00:00
a48de5fed2 Update src/app/login/page.tsx 2026-03-11 19:54:53 +00:00
40357c2c40 Update src/app/page.tsx 2026-03-11 19:47:42 +00:00
3180013673 Update src/app/signup/page.tsx 2026-03-11 19:44:57 +00:00
093309937b Update src/app/page.tsx 2026-03-11 19:44:57 +00:00
308dee7afe Update src/app/login/page.tsx 2026-03-11 19:44:56 +00:00
f9e55abdf0 Add src/app/lib/storage/workoutStorage.ts 2026-03-11 19:44:56 +00:00
88623e3b9b Add src/app/hooks/useWorkoutTracking.ts 2026-03-11 19:44:55 +00:00
d0afbe9b1f Add src/app/components/WorkoutDataIntegration.tsx 2026-03-11 19:44:55 +00:00
005a296b9a Update src/components/cardStack/layouts/grid/GridLayout.tsx 2026-03-11 19:40:13 +00:00
77ff7ff4d4 Update src/components/cardStack/layouts/carousels/ButtonCarousel.tsx 2026-03-11 19:40:12 +00:00
93aefd0c57 Update src/components/cardStack/layouts/carousels/AutoCarousel.tsx 2026-03-11 19:40:12 +00:00
ae76a7cff6 Update src/app/page.tsx 2026-03-11 19:40:11 +00:00
488e2a5c51 Update src/components/sections/product/ProductCardOne.tsx 2026-03-11 19:39:15 +00:00
b129bfd9cf Update src/components/sections/about/SplitAbout.tsx 2026-03-11 19:39:14 +00:00
b28bd2dcf5 Update src/components/ecommerce/productCatalog/ProductCatalog.tsx 2026-03-11 19:39:14 +00:00
fe2f8fa0ee Update src/components/cardStack/types.ts 2026-03-11 19:39:14 +00:00
cfa9842e81 Update src/components/cardStack/layouts/timelines/TimelineProcessFlow.tsx 2026-03-11 19:39:13 +00:00
212fa0122f Update src/components/cardStack/layouts/timelines/TimelinePhoneView.tsx 2026-03-11 19:39:13 +00:00
9655cab4e3 Update src/components/cardStack/layouts/timelines/TimelineHorizontalCardStack.tsx 2026-03-11 19:39:12 +00:00
82c0af05a8 Update src/components/cardStack/layouts/timelines/TimelineCardStack.tsx 2026-03-11 19:39:12 +00:00
1309e7295d Update src/components/cardStack/layouts/grid/GridLayout.tsx 2026-03-11 19:39:11 +00:00
31465a8ae9 Update src/components/cardStack/layouts/carousels/FullWidthCarousel.tsx 2026-03-11 19:39:11 +00:00
ce18a6ba19 Update src/components/cardStack/layouts/carousels/ButtonCarousel.tsx 2026-03-11 19:39:11 +00:00
c9969a0209 Update src/components/cardStack/layouts/carousels/AutoCarousel.tsx 2026-03-11 19:39:10 +00:00
c215ee186a Update src/components/cardStack/layouts/carousels/ArrowCarousel.tsx 2026-03-11 19:39:10 +00:00
bf9e7f8fc5 Update src/components/cardStack/hooks/useCardAnimation.ts 2026-03-11 19:39:09 +00:00
fae97b71b9 Update src/components/cardStack/CardStackTextBox.tsx 2026-03-11 19:39:09 +00:00
7c7492a61d Update src/components/cardStack/CardStack.tsx 2026-03-11 19:39:09 +00:00
a8b88e122a Update src/components/cardStack/CardList.tsx 2026-03-11 19:39:08 +00:00
742e1b3207 Update src/lib/storage/workoutStorage.ts 2026-03-11 19:34:32 +00:00
696d96576f Update src/lib/api/product.ts 2026-03-11 19:34:32 +00:00
d72002cc2a Update src/hooks/useWorkoutData.ts 2026-03-11 19:34:31 +00:00
47c67cf895 Update src/hooks/useProducts.ts 2026-03-11 19:34:31 +00:00
2f0a871780 Update src/hooks/useProduct.ts 2026-03-11 19:34:30 +00:00
a61b9e7295 Update src/components/workout/WorkoutSaver.tsx 2026-03-11 19:34:30 +00:00
5e98ca450b Update src/components/sections/product/ProductCardTwo.tsx 2026-03-11 19:34:30 +00:00
6c2e2023b8 Update src/components/sections/product/ProductCardThree.tsx 2026-03-11 19:34:29 +00:00
82e318beba Update src/components/sections/product/ProductCardOne.tsx 2026-03-11 19:34:29 +00:00
d3e11ac10b Update src/components/sections/product/ProductCardFour.tsx 2026-03-11 19:34:28 +00:00
c4e99d4455 Update src/components/sections/contact/ContactSplitForm.tsx 2026-03-11 19:34:28 +00:00
ba5d18bcdc Update src/components/sections/contact/ContactSplit.tsx 2026-03-11 19:34:28 +00:00
aaec945205 Update src/components/sections/contact/ContactCenter.tsx 2026-03-11 19:34:27 +00:00
d1b23d0149 Update src/components/cardStack/types.ts 2026-03-11 19:34:27 +00:00
711538ea72 Update src/components/cardStack/hooks/useCardAnimation.ts 2026-03-11 19:34:26 +00:00
00d4a3cc07 Update src/lib/storage/workoutStorage.ts 2026-03-11 19:33:41 +00:00
bb58f2b1f7 Update src/lib/api/product.ts 2026-03-11 19:33:41 +00:00
b76a65f105 Update src/hooks/useProductDetail.ts 2026-03-11 19:33:40 +00:00
c17cec6858 Update src/hooks/useProductCatalog.ts 2026-03-11 19:33:40 +00:00
a970fa211a Update src/hooks/useCheckout.ts 2026-03-11 19:33:39 +00:00
fb4de8b486 Update src/components/workout/WorkoutMetricsDisplay.tsx 2026-03-11 19:33:39 +00:00
432bdc5bf5 Update src/components/sections/pricing/PricingCardEight.tsx 2026-03-11 19:33:39 +00:00
f74e65ef38 Update src/components/sections/contact/ContactSplitForm.tsx 2026-03-11 19:33:38 +00:00
ed48cbb8e4 Update src/components/sections/contact/ContactSplit.tsx 2026-03-11 19:33:38 +00:00
0776a4bc86 Update src/components/sections/contact/ContactCenter.tsx 2026-03-11 19:33:37 +00:00
12839b702d Update src/components/cardStack/layouts/timelines/TimelineBase.tsx 2026-03-11 19:33:37 +00:00
bcfa66f6e1 Update src/components/cardStack/hooks/useDepth3DAnimation.ts 2026-03-11 19:33:36 +00:00
ddd6eb99a0 Update src/components/workout/WorkoutSaver.tsx 2026-03-11 19:32:44 +00:00
8f7f54d74f Add src/lib/storage/workoutStorage.ts 2026-03-11 19:32:12 +00:00
4ba888b3a1 Add src/hooks/useWorkoutData.ts 2026-03-11 19:32:12 +00:00
8924fed85c Add src/components/workout/WorkoutSaver.tsx 2026-03-11 19:32:11 +00:00
3fba97bf22 Add src/components/workout/WorkoutMetricsDisplay.tsx 2026-03-11 19:32:11 +00:00
f7e85fec99 Add src/app/signup/page.tsx 2026-03-11 19:32:10 +00:00
aad94e4324 Update src/app/page.tsx 2026-03-11 19:32:10 +00:00
3aa2c9a181 Add src/app/login/page.tsx 2026-03-11 19:32:10 +00:00
896fe7132d Merge version_1 into main
Merge version_1 into main
2026-03-11 19:24:25 +00:00
865bd7dba2 Merge version_1 into main
Merge version_1 into main
2026-03-11 19:24:01 +00:00
47 changed files with 2614 additions and 5218 deletions

View File

@@ -0,0 +1,64 @@
'use client';
import React, { useCallback } from 'react';
import { useWorkoutTracking } from '@/app/hooks/useWorkoutTracking';
import { WorkoutSession, CardioSession, NutritionLog } from '@/app/lib/storage/workoutStorage';
export interface WorkoutDataIntegrationProps {
onSave?: (data: any) => void;
autoSave?: boolean;
}
/**
* WorkoutDataIntegration component that provides workout tracking context
* Use this component to wrap sections that need to save workout data
*/
export const WorkoutDataIntegration: React.FC<{
children: React.ReactNode;
} & WorkoutDataIntegrationProps> = ({ children, onSave, autoSave = true }) => {
const { metrics, addWorkoutSession, addCardioSession, addNutritionLog, refreshMetrics } =
useWorkoutTracking();
const handleWorkoutSave = useCallback(
(session: WorkoutSession) => {
addWorkoutSession(session);
if (onSave) onSave({ type: 'workout', data: session });
},
[addWorkoutSession, onSave]
);
const handleCardioSave = useCallback(
(session: CardioSession) => {
addCardioSession(session);
if (onSave) onSave({ type: 'cardio', data: session });
},
[addCardioSession, onSave]
);
const handleNutritionSave = useCallback(
(log: NutritionLog) => {
addNutritionLog(log);
if (onSave) onSave({ type: 'nutrition', data: log });
},
[addNutritionLog, onSave]
);
// Expose save functions via context or props
const contextValue = {
metrics,
handleWorkoutSave,
handleCardioSave,
handleNutritionSave,
refreshMetrics,
autoSave,
};
// Clone children and pass context data as props
return (
<div data-workout-integration="true" data-context={JSON.stringify(contextValue)}>
{children}
</div>
);
};
export default WorkoutDataIntegration;

View File

@@ -0,0 +1,56 @@
'use client';
import { useState, useCallback } from 'react';
import {
saveWorkoutSession,
saveCardioSession,
saveNutritionLog,
getUserMetrics,
getWorkoutSessions,
getCardioSessions,
getNutritionLogs,
WorkoutSession,
CardioSession,
NutritionLog,
UserMetrics,
} from '@/app/lib/storage/workoutStorage';
export const useWorkoutTracking = () => {
const [metrics, setMetrics] = useState<UserMetrics>(getUserMetrics());
const [workouts, setWorkouts] = useState<WorkoutSession[]>(getWorkoutSessions());
const [cardioSessions, setCardioSessions] = useState<CardioSession[]>(getCardioSessions());
const [nutritionLogs, setNutritionLogs] = useState<NutritionLog[]>(getNutritionLogs());
const addWorkoutSession = useCallback((session: WorkoutSession) => {
saveWorkoutSession(session);
setWorkouts(getWorkoutSessions());
setMetrics(getUserMetrics());
}, []);
const addCardioSession = useCallback((session: CardioSession) => {
saveCardioSession(session);
setCardioSessions(getCardioSessions());
setMetrics(getUserMetrics());
}, []);
const addNutritionLog = useCallback((log: NutritionLog) => {
saveNutritionLog(log);
setNutritionLogs(getNutritionLogs());
setMetrics(getUserMetrics());
}, []);
const refreshMetrics = useCallback(() => {
setMetrics(getUserMetrics());
}, []);
return {
metrics,
workouts,
cardioSessions,
nutritionLogs,
addWorkoutSession,
addCardioSession,
addNutritionLog,
refreshMetrics,
};
};

View File

@@ -0,0 +1,309 @@
/**
* Workout and metrics data persistence layer
* Handles saving and retrieving workout data from localStorage
*/
export interface WorkoutSet {
reps: number;
weight: number;
timestamp: number;
}
export interface WorkoutSession {
id: string;
exerciseName: string;
date: string;
sets: WorkoutSet[];
duration: number; // in seconds
caloriesBurned: number;
notes?: string;
}
export interface CardioSession {
id: string;
type: 'running' | 'walking' | 'cycling';
date: string;
distance: number; // in km
duration: number; // in seconds
caloriesBurned: number;
pace: number; // km/h
steps?: number;
route?: string;
}
export interface NutritionLog {
id: string;
date: string;
calories: number;
protein: number;
carbs: number;
fats: number;
meals: string[];
}
export interface UserMetrics {
totalWorkouts: number;
totalCardioDistance: number;
totalCaloriesBurned: number;
currentStreak: number;
personalRecords: Record<string, number>;
lastUpdated: number;
}
const STORAGE_KEYS = {
WORKOUT_SESSIONS: 'fitflow_workout_sessions',
CARDIO_SESSIONS: 'fitflow_cardio_sessions',
NUTRITION_LOGS: 'fitflow_nutrition_logs',
USER_METRICS: 'fitflow_user_metrics',
};
/**
* Save a workout session to localStorage
*/
export const saveWorkoutSession = (session: WorkoutSession): void => {
if (typeof window === 'undefined') return;
try {
const sessions = getWorkoutSessions();
sessions.push(session);
localStorage.setItem(STORAGE_KEYS.WORKOUT_SESSIONS, JSON.stringify(sessions));
updateUserMetrics();
} catch (error) {
console.error('Error saving workout session:', error);
}
};
/**
* Get all workout sessions from localStorage
*/
export const getWorkoutSessions = (): WorkoutSession[] => {
if (typeof window === 'undefined') return [];
try {
const data = localStorage.getItem(STORAGE_KEYS.WORKOUT_SESSIONS);
return data ? JSON.parse(data) : [];
} catch (error) {
console.error('Error retrieving workout sessions:', error);
return [];
}
};
/**
* Save a cardio session to localStorage
*/
export const saveCardioSession = (session: CardioSession): void => {
if (typeof window === 'undefined') return;
try {
const sessions = getCardioSessions();
sessions.push(session);
localStorage.setItem(STORAGE_KEYS.CARDIO_SESSIONS, JSON.stringify(sessions));
updateUserMetrics();
} catch (error) {
console.error('Error saving cardio session:', error);
}
};
/**
* Get all cardio sessions from localStorage
*/
export const getCardioSessions = (): CardioSession[] => {
if (typeof window === 'undefined') return [];
try {
const data = localStorage.getItem(STORAGE_KEYS.CARDIO_SESSIONS);
return data ? JSON.parse(data) : [];
} catch (error) {
console.error('Error retrieving cardio sessions:', error);
return [];
}
};
/**
* Save a nutrition log to localStorage
*/
export const saveNutritionLog = (log: NutritionLog): void => {
if (typeof window === 'undefined') return;
try {
const logs = getNutritionLogs();
logs.push(log);
localStorage.setItem(STORAGE_KEYS.NUTRITION_LOGS, JSON.stringify(logs));
updateUserMetrics();
} catch (error) {
console.error('Error saving nutrition log:', error);
}
};
/**
* Get all nutrition logs from localStorage
*/
export const getNutritionLogs = (): NutritionLog[] => {
if (typeof window === 'undefined') return [];
try {
const data = localStorage.getItem(STORAGE_KEYS.NUTRITION_LOGS);
return data ? JSON.parse(data) : [];
} catch (error) {
console.error('Error retrieving nutrition logs:', error);
return [];
}
};
/**
* Get user metrics from localStorage
*/
export const getUserMetrics = (): UserMetrics => {
if (typeof window === 'undefined') {
return {
totalWorkouts: 0,
totalCardioDistance: 0,
totalCaloriesBurned: 0,
currentStreak: 0,
personalRecords: {},
lastUpdated: Date.now(),
};
}
try {
const data = localStorage.getItem(STORAGE_KEYS.USER_METRICS);
return data
? JSON.parse(data)
: {
totalWorkouts: 0,
totalCardioDistance: 0,
totalCaloriesBurned: 0,
currentStreak: 0,
personalRecords: {},
lastUpdated: Date.now(),
};
} catch (error) {
console.error('Error retrieving user metrics:', error);
return {
totalWorkouts: 0,
totalCardioDistance: 0,
totalCaloriesBurned: 0,
currentStreak: 0,
personalRecords: {},
lastUpdated: Date.now(),
};
}
};
/**
* Update user metrics based on saved sessions
*/
export const updateUserMetrics = (): void => {
if (typeof window === 'undefined') return;
try {
const workoutSessions = getWorkoutSessions();
const cardioSessions = getCardioSessions();
const nutritionLogs = getNutritionLogs();
let totalWorkouts = workoutSessions.length;
let totalCardioDistance = cardioSessions.reduce((sum, session) => sum + session.distance, 0);
let totalCaloriesBurned = workoutSessions.reduce((sum, session) => sum + session.caloriesBurned, 0)
+ cardioSessions.reduce((sum, session) => sum + session.caloriesBurned, 0);
// Calculate streak (consecutive days with activity)
const currentStreak = calculateStreak([...workoutSessions, ...cardioSessions]);
// Extract personal records from workouts
const personalRecords: Record<string, number> = {};
workoutSessions.forEach((session) => {
const maxWeight = Math.max(...session.sets.map((s) => s.weight));
const key = `${session.exerciseName}_pr`;
if (!personalRecords[key] || maxWeight > personalRecords[key]) {
personalRecords[key] = maxWeight;
}
});
const metrics: UserMetrics = {
totalWorkouts,
totalCardioDistance,
totalCaloriesBurned,
currentStreak,
personalRecords,
lastUpdated: Date.now(),
};
localStorage.setItem(STORAGE_KEYS.USER_METRICS, JSON.stringify(metrics));
} catch (error) {
console.error('Error updating user metrics:', error);
}
};
/**
* Calculate consecutive days with activity
*/
const calculateStreak = (sessions: Array<WorkoutSession | CardioSession>): number => {
if (sessions.length === 0) return 0;
const dates = sessions.map((session) => new Date(session.date).toDateString()).filter((date, index, self) => self.indexOf(date) === index).sort((a, b) => new Date(b).getTime() - new Date(a).getTime());
let streak = 1;
for (let i = 1; i < dates.length; i++) {
const currentDate = new Date(dates[i]);
const previousDate = new Date(dates[i - 1]);
const diffTime = Math.abs(previousDate.getTime() - currentDate.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 1) {
streak++;
} else {
break;
}
}
return streak;
};
/**
* Clear all stored data
*/
export const clearAllData = (): void => {
if (typeof window === 'undefined') return;
try {
localStorage.removeItem(STORAGE_KEYS.WORKOUT_SESSIONS);
localStorage.removeItem(STORAGE_KEYS.CARDIO_SESSIONS);
localStorage.removeItem(STORAGE_KEYS.NUTRITION_LOGS);
localStorage.removeItem(STORAGE_KEYS.USER_METRICS);
} catch (error) {
console.error('Error clearing data:', error);
}
};
/**
* Export data as JSON for backup
*/
export const exportData = (): string => {
const data = {
workouts: getWorkoutSessions(),
cardio: getCardioSessions(),
nutrition: getNutritionLogs(),
metrics: getUserMetrics(),
exportDate: new Date().toISOString(),
};
return JSON.stringify(data, null, 2);
};
/**
* Import data from JSON backup
*/
export const importData = (jsonData: string): boolean => {
if (typeof window === 'undefined') return false;
try {
const data = JSON.parse(jsonData);
if (data.workouts) localStorage.setItem(STORAGE_KEYS.WORKOUT_SESSIONS, JSON.stringify(data.workouts));
if (data.cardio) localStorage.setItem(STORAGE_KEYS.CARDIO_SESSIONS, JSON.stringify(data.cardio));
if (data.nutrition) localStorage.setItem(STORAGE_KEYS.NUTRITION_LOGS, JSON.stringify(data.nutrition));
if (data.metrics) localStorage.setItem(STORAGE_KEYS.USER_METRICS, JSON.stringify(data.metrics));
return true;
} catch (error) {
console.error('Error importing data:', error);
return false;
}
};

259
src/app/login/page.tsx Normal file
View File

@@ -0,0 +1,259 @@
"use client";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import ContactCTA from '@/components/sections/contact/ContactCTA';
import FooterLogoEmphasis from '@/components/sections/footer/FooterLogoEmphasis';
import { Mail, Lock, ArrowRight, AlertCircle } from 'lucide-react';
import { useState } from 'react';
export default function LoginPage() {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const [errors, setErrors] = useState<{ [key: string]: string }>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const validateForm = () => {
const newErrors: { [key: string]: string } = {};
if (!formData.email) {
newErrors.email = 'Email é obrigatório';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Email inválido';
}
if (!formData.password) {
newErrors.password = 'Senha é obrigatória';
} else if (formData.password.length < 6) {
newErrors.password = 'Senha deve ter pelo menos 6 caracteres';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
if (errors[name]) {
setErrors(prev => ({
...prev,
[name]: ''
}));
}
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validateForm()) {
return;
}
setIsSubmitting(true);
try {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Login attempt:', formData);
alert('Login bem-sucedido!');
setFormData({ email: '', password: '' });
} catch (error) {
setErrors({ submit: 'Erro ao fazer login. Tente novamente.' });
} finally {
setIsSubmitting(false);
}
};
return (
<ThemeProvider
defaultButtonVariant="elastic-effect"
defaultTextAnimation="entrance-slide"
borderRadius="pill"
contentWidth="smallMedium"
sizing="mediumSizeLargeTitles"
background="blurBottom"
cardStyle="gradient-bordered"
primaryButtonStyle="flat"
secondaryButtonStyle="glass"
headingFontWeight="extrabold"
>
<div id="nav" data-section="nav">
<NavbarStyleCentered
navItems={[
{ name: "Dashboard", id: "/" },
{ name: "Sobre", id: "#hero" },
{ name: "Features", id: "#onboarding" },
{ name: "Contato", id: "#contact" },
{ name: "Signup", id: "/signup" }
]}
button={{ text: "Fazer Login", href: "/login" }}
brandName="FitFlow Pro"
/>
</div>
<div id="login" data-section="login" className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div className="w-full max-w-md space-y-8">
<div className="text-center space-y-3">
<h1 className="text-4xl font-extrabold tracking-tight">Bem-vindo de volta</h1>
<p className="text-base text-gray-600 dark:text-gray-400">Faça login na sua conta FitFlow Pro</p>
</div>
<div className="bg-card rounded-2xl border border-primary-cta/20 p-8 shadow-lg">
<form onSubmit={handleSubmit} className="space-y-6">
{/* Email Field */}
<div className="space-y-2">
<label htmlFor="email" className="block text-sm font-medium text-foreground">
Email
</label>
<div className="relative">
<Mail className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="seu@email.com"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.email
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{errors.email && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.email}
</div>
)}
</div>
{/* Password Field */}
<div className="space-y-2">
<label htmlFor="password" className="block text-sm font-medium text-foreground">
Senha
</label>
<div className="relative">
<Lock className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
placeholder="••••••••"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.password
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{errors.password && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.password}
</div>
)}
</div>
{/* Submit Errors */}
{errors.submit && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{errors.submit}
</div>
)}
{/* Submit Button */}
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-primary-cta hover:bg-primary-cta/90 text-white font-semibold py-2.5 rounded-lg transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Entrando...' : 'Fazer Login'}
{!isSubmitting && <ArrowRight className="w-4 h-4" />}
</button>
</form>
{/* Divider */}
<div className="mt-6 relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-card text-gray-500">ou continue com</span>
</div>
</div>
{/* Social Login Buttons */}
<div className="mt-6 space-y-3">
<button className="w-full bg-background hover:bg-gray-50 dark:hover:bg-gray-800 border border-gray-300 dark:border-gray-600 text-foreground font-medium py-2.5 rounded-lg transition-all">
Google
</button>
<button className="w-full bg-background hover:bg-gray-50 dark:hover:bg-gray-800 border border-gray-300 dark:border-gray-600 text-foreground font-medium py-2.5 rounded-lg transition-all">
Apple
</button>
</div>
</div>
{/* Sign Up Link */}
<p className="text-center text-gray-600 dark:text-gray-400 text-sm">
Não tem conta?{' '}
<a href="/signup" className="text-primary-cta hover:text-primary-cta/80 font-semibold transition-colors">
Criar conta
</a>
</p>
{/* Forgot Password Link */}
<p className="text-center text-gray-600 dark:text-gray-400 text-sm">
<a href="#" className="text-primary-cta hover:text-primary-cta/80 font-semibold transition-colors">
Esqueceu sua senha?
</a>
</p>
</div>
</div>
<div id="footer" data-section="footer">
<FooterLogoEmphasis
columns={[
{
items: [
{ label: "Home", href: "/" },
{ label: "Sobre", href: "/#hero" },
{ label: "Features", href: "/#onboarding" }
]
},
{
items: [
{ label: "Blog", href: "#" },
{ label: "Ajuda", href: "#" },
{ label: "Suporte", href: "#" }
]
},
{
items: [
{ label: "Privacidade", href: "#" },
{ label: "Termos", href: "#" },
{ label: "Contato", href: "#" }
]
},
{
items: [
{ label: "Login", href: "/login" },
{ label: "Signup", href: "/signup" },
{ label: "Dashboard", href: "/" }
]
}
]}
logoText="FitFlow Pro"
/>
</div>
</ThemeProvider>
);
}

View File

@@ -15,6 +15,29 @@ import FooterLogoEmphasis from '@/components/sections/footer/FooterLogoEmphasis'
import { Activity, Apple, Brain, Dumbbell, Heart, Target, Zap, Users, Star, TrendingDown, TrendingUp } from 'lucide-react'; import { Activity, Apple, Brain, Dumbbell, Heart, Target, Zap, Users, Star, TrendingDown, TrendingUp } from 'lucide-react';
export default function LandingPage() { export default function LandingPage() {
const displayMetrics = [
{ id: "1", value: "10.000+", description: "Passos diários rastreados em tempo real com motivação visual de progresso." },
{ id: "2", value: "500 kg", description: "Volume total de peso levantado monitorado com progressão semanal automática." },
{ id: "3", value: "150+ km", description: "Distância corrida mapeada com GPS, ritmo calculado e calorias precisas." },
{ id: "4", value: "42 dias", description: "Sequência de treinos consistentes com badges de dedicação desbloqueados." }
];
const handleCardioInteraction = (data: any) => {
console.log('Cardio interaction:', data);
};
const handleTrainingInteraction = (data: any) => {
console.log('Training interaction:', data);
};
const handleWorkoutMode = (productId: string, productName: string) => {
console.log('Workout mode:', productId, productName);
};
const handleNutritionSelect = (planId: string, planName: string) => {
console.log('Nutrition select:', planId, planName);
};
return ( return (
<ThemeProvider <ThemeProvider
defaultButtonVariant="elastic-effect" defaultButtonVariant="elastic-effect"
@@ -188,13 +211,13 @@ export default function LandingPage() {
tagIcon={Target} tagIcon={Target}
products={[ products={[
{ {
id: "1", name: "Iniciar Série", price: "Botão Proeminente", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/workout-execution-interface-showing-set--1773256980664-da11c464.png?_wi=3", imageAlt: "Tela de série" id: "1", name: "Iniciar Série", price: "Botão Proeminente", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/workout-execution-interface-showing-set--1773256980664-da11c464.png?_wi=3", imageAlt: "Tela de série", onProductClick: () => handleWorkoutMode("1", "Iniciar Série")
}, },
{ {
id: "2", name: "Cronômetro de Descanso", price: "Automático", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/workout-execution-interface-showing-set--1773256980664-da11c464.png?_wi=4", imageAlt: "Descanso entre séries" id: "2", name: "Cronômetro de Descanso", price: "Automático", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/workout-execution-interface-showing-set--1773256980664-da11c464.png?_wi=4", imageAlt: "Descanso entre séries", onProductClick: () => handleWorkoutMode("2", "Cronômetro de Descanso")
}, },
{ {
id: "3", name: "Registrar Progresso", price: "Carga + Reps", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/performance-metrics-showcase-displaying--1773256982260-f9a5cff0.png?_wi=4", imageAlt: "Progresso salvo" id: "3", name: "Registrar Progresso", price: "Carga + Reps", imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/users/user_3AoRNSPr0mCBj85JKsHl7qxTHsl/performance-metrics-showcase-displaying--1773256982260-f9a5cff0.png?_wi=4", imageAlt: "Progresso salvo", onProductClick: () => handleWorkoutMode("3", "Registrar Progresso")
} }
]} ]}
animationType="slide-up" animationType="slide-up"
@@ -235,20 +258,7 @@ export default function LandingPage() {
title="Suas Conquistas Importam. Veja Cada Número." title="Suas Conquistas Importam. Veja Cada Número."
tag="Performance Metrics" tag="Performance Metrics"
tagAnimation="slide-up" tagAnimation="slide-up"
metrics={[ metrics={displayMetrics}
{
id: "1", value: "10.000+", description: "Passos diários rastreados em tempo real com motivação visual de progresso."
},
{
id: "2", value: "500 kg", description: "Volume total de peso levantado monitorado com progressão semanal automática."
},
{
id: "3", value: "150+ km", description: "Distância corrida mapeada com GPS, ritmo calculado e calorias precisas."
},
{
id: "4", value: "42 dias", description: "Sequência de treinos consistentes com badges de dedicação desbloqueados."
}
]}
metricsAnimation="slide-up" metricsAnimation="slide-up"
useInvertedBackground={false} useInvertedBackground={false}
/> />

428
src/app/signup/page.tsx Normal file
View File

@@ -0,0 +1,428 @@
"use client";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import ContactCTA from '@/components/sections/contact/ContactCTA';
import FooterLogoEmphasis from '@/components/sections/footer/FooterLogoEmphasis';
import { Mail, Lock, User, AlertCircle, Check, ArrowRight } from 'lucide-react';
import { useState } from 'react';
interface FormErrors {
[key: string]: string;
}
interface SignupFormData {
name: string;
email: string;
password: string;
confirmPassword: string;
agreedToTerms: boolean;
}
export default function SignupPage() {
const [formData, setFormData] = useState<SignupFormData>({
name: '',
email: '',
password: '',
confirmPassword: '',
agreedToTerms: false
});
const [errors, setErrors] = useState<FormErrors>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [passwordStrength, setPasswordStrength] = useState(0);
const calculatePasswordStrength = (password: string) => {
let strength = 0;
if (password.length >= 8) strength++;
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
if (/\d/.test(password)) strength++;
if (/[^a-zA-Z\d]/.test(password)) strength++;
setPasswordStrength(strength);
};
const validateForm = () => {
const newErrors: FormErrors = {};
if (!formData.name.trim()) {
newErrors.name = 'Nome é obrigatório';
} else if (formData.name.length < 2) {
newErrors.name = 'Nome deve ter pelo menos 2 caracteres';
}
if (!formData.email) {
newErrors.email = 'Email é obrigatório';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Email inválido';
}
if (!formData.password) {
newErrors.password = 'Senha é obrigatória';
} else if (formData.password.length < 8) {
newErrors.password = 'Senha deve ter pelo menos 8 caracteres';
}
if (formData.password !== formData.confirmPassword) {
newErrors.confirmPassword = 'As senhas não correspondem';
}
if (!formData.agreedToTerms) {
newErrors.agreedToTerms = 'Você deve aceitar os termos e condições';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value, type, checked } = e.target;
const newValue = type === 'checkbox' ? checked : value;
setFormData(prev => ({
...prev,
[name]: newValue
}));
if (errors[name]) {
setErrors(prev => ({
...prev,
[name]: ''
}));
}
if (name === 'password') {
calculatePasswordStrength(value);
}
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validateForm()) {
return;
}
setIsSubmitting(true);
try {
await new Promise(resolve => setTimeout(resolve, 1500));
console.log('Signup attempt:', formData);
alert('Conta criada com sucesso! Faça login para continuar.');
setFormData({
name: '',
email: '',
password: '',
confirmPassword: '',
agreedToTerms: false
});
setPasswordStrength(0);
} catch (error) {
setErrors({ submit: 'Erro ao criar conta. Tente novamente.' });
} finally {
setIsSubmitting(false);
}
};
const getPasswordStrengthColor = () => {
if (passwordStrength === 0) return 'bg-gray-300';
if (passwordStrength === 1) return 'bg-red-500';
if (passwordStrength === 2) return 'bg-yellow-500';
if (passwordStrength === 3) return 'bg-blue-500';
return 'bg-green-500';
};
const getPasswordStrengthLabel = () => {
if (passwordStrength === 0) return '';
if (passwordStrength === 1) return 'Fraca';
if (passwordStrength === 2) return 'Média';
if (passwordStrength === 3) return 'Forte';
return 'Muito Forte';
};
return (
<ThemeProvider
defaultButtonVariant="elastic-effect"
defaultTextAnimation="entrance-slide"
borderRadius="pill"
contentWidth="smallMedium"
sizing="mediumSizeLargeTitles"
background="blurBottom"
cardStyle="gradient-bordered"
primaryButtonStyle="flat"
secondaryButtonStyle="glass"
headingFontWeight="extrabold"
>
<div id="nav" data-section="nav">
<NavbarStyleCentered
navItems={[
{ name: "Dashboard", id: "/" },
{ name: "Sobre", id: "#hero" },
{ name: "Features", id: "#onboarding" },
{ name: "Contato", id: "#contact" },
{ name: "Login", id: "/login" }
]}
button={{ text: "Criar Conta", href: "/signup" }}
brandName="FitFlow Pro"
/>
</div>
<div id="signup" data-section="signup" className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div className="w-full max-w-md space-y-8">
<div className="text-center space-y-3">
<h1 className="text-4xl font-extrabold tracking-tight">Comece sua jornada</h1>
<p className="text-base text-gray-600 dark:text-gray-400">Crie sua conta FitFlow Pro e transforme seu corpo</p>
</div>
<div className="bg-card rounded-2xl border border-primary-cta/20 p-8 shadow-lg">
<form onSubmit={handleSubmit} className="space-y-5">
{/* Name Field */}
<div className="space-y-2">
<label htmlFor="name" className="block text-sm font-medium text-foreground">
Nome Completo
</label>
<div className="relative">
<User className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="name"
name="name"
type="text"
value={formData.name}
onChange={handleChange}
placeholder="Seu nome"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.name
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{errors.name && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.name}
</div>
)}
</div>
{/* Email Field */}
<div className="space-y-2">
<label htmlFor="email" className="block text-sm font-medium text-foreground">
Email
</label>
<div className="relative">
<Mail className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="seu@email.com"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.email
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{errors.email && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.email}
</div>
)}
</div>
{/* Password Field */}
<div className="space-y-2">
<label htmlFor="password" className="block text-sm font-medium text-foreground">
Senha
</label>
<div className="relative">
<Lock className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
placeholder="••••••••••"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.password
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{formData.password && (
<div className="space-y-2">
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5 overflow-hidden">
<div
className={`h-full transition-all ${getPasswordStrengthColor()}`}
style={{ width: `${(passwordStrength / 4) * 100}%` }}
></div>
</div>
<p className="text-xs text-gray-600 dark:text-gray-400">
Força: <span className="font-semibold">{getPasswordStrengthLabel()}</span>
</p>
</div>
)}
{errors.password && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.password}
</div>
)}
</div>
{/* Confirm Password Field */}
<div className="space-y-2">
<label htmlFor="confirmPassword" className="block text-sm font-medium text-foreground">
Confirmar Senha
</label>
<div className="relative">
<Lock className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
id="confirmPassword"
name="confirmPassword"
type="password"
value={formData.confirmPassword}
onChange={handleChange}
placeholder="••••••••••"
className={`w-full pl-10 pr-4 py-2.5 bg-background border rounded-lg focus:outline-none focus:ring-2 transition-all ${
errors.confirmPassword
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-primary-cta'
}`}
/>
</div>
{formData.confirmPassword && formData.password === formData.confirmPassword && !errors.confirmPassword && (
<div className="flex items-center gap-2 text-green-500 text-sm">
<Check className="w-4 h-4" />
Senhas correspondem
</div>
)}
{errors.confirmPassword && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.confirmPassword}
</div>
)}
</div>
{/* Terms Checkbox */}
<div className="space-y-2">
<div className="flex items-start gap-3">
<input
id="agreedToTerms"
name="agreedToTerms"
type="checkbox"
checked={formData.agreedToTerms}
onChange={handleChange}
className="w-5 h-5 mt-0.5 rounded border-gray-300 accent-primary-cta cursor-pointer"
/>
<label htmlFor="agreedToTerms" className="text-sm text-gray-600 dark:text-gray-400 cursor-pointer">
Concordo com os{' '}
<a href="#" className="text-primary-cta hover:underline font-semibold">
termos de serviço
</a>
{' '}e{' '}
<a href="#" className="text-primary-cta hover:underline font-semibold">
política de privacidade
</a>
</label>
</div>
{errors.agreedToTerms && (
<div className="flex items-center gap-2 text-red-500 text-sm">
<AlertCircle className="w-4 h-4" />
{errors.agreedToTerms}
</div>
)}
</div>
{/* Submit Errors */}
{errors.submit && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{errors.submit}
</div>
)}
{/* Submit Button */}
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-primary-cta hover:bg-primary-cta/90 text-white font-semibold py-2.5 rounded-lg transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Criando conta...' : 'Criar Conta'}
{!isSubmitting && <ArrowRight className="w-4 h-4" />}
</button>
</form>
{/* Divider */}
<div className="mt-6 relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-card text-gray-500">ou continue com</span>
</div>
</div>
{/* Social Signup Buttons */}
<div className="mt-6 space-y-3">
<button className="w-full bg-background hover:bg-gray-50 dark:hover:bg-gray-800 border border-gray-300 dark:border-gray-600 text-foreground font-medium py-2.5 rounded-lg transition-all">
Google
</button>
<button className="w-full bg-background hover:bg-gray-50 dark:hover:bg-gray-800 border border-gray-300 dark:border-gray-600 text-foreground font-medium py-2.5 rounded-lg transition-all">
Apple
</button>
</div>
</div>
{/* Login Link */}
<p className="text-center text-gray-600 dark:text-gray-400 text-sm">
tem conta?{' '}
<a href="/login" className="text-primary-cta hover:text-primary-cta/80 font-semibold transition-colors">
Fazer login
</a>
</p>
</div>
</div>
<div id="footer" data-section="footer">
<FooterLogoEmphasis
columns={[
{
items: [
{ label: "Home", href: "/" },
{ label: "Sobre", href: "/#hero" },
{ label: "Features", href: "/#onboarding" }
]
},
{
items: [
{ label: "Blog", href: "#" },
{ label: "Ajuda", href: "#" },
{ label: "Suporte", href: "#" }
]
},
{
items: [
{ label: "Privacidade", href: "#" },
{ label: "Termos", href: "#" },
{ label: "Contato", href: "#" }
]
},
{
items: [
{ label: "Login", href: "/login" },
{ label: "Signup", href: "/signup" },
{ label: "Dashboard", href: "/" }
]
}
]}
logoText="FitFlow Pro"
/>
</div>
</ThemeProvider>
);
}

View File

@@ -1,123 +1,26 @@
"use client"; 'use client';
import { memo, Children } from "react"; import React, { useRef } from 'react';
import CardStackTextBox from "@/components/cardStack/CardStackTextBox"; import { ButtonConfig, ButtonAnimationType, CardAnimationType, TitleSegment } from '@/components/cardStack/types';
import { useCardAnimation } from "@/components/cardStack/hooks/useCardAnimation";
import { cls } from "@/lib/utils";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, ButtonAnimationType, CardAnimationType, TitleSegment } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
interface CardListProps { interface CardListProps {
children: React.ReactNode; items: any[];
animationType: CardAnimationType;
useUncappedRounding?: boolean;
title?: string;
titleSegments?: TitleSegment[];
description?: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground?: InvertedBackground;
disableCardWrapper?: boolean;
ariaLabel?: string;
className?: string; className?: string;
containerClassName?: string;
cardClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
} }
const CardList = ({ const CardList: React.FC<CardListProps> = ({ items, className = '' }) => {
children, const itemRefs = useRef<(HTMLElement | null)[]>([]);
animationType,
useUncappedRounding = false,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
disableCardWrapper = false,
ariaLabel = "Card list",
className = "",
containerClassName = "",
cardClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
}: CardListProps) => {
const childrenArray = Children.toArray(children);
const { itemRefs } = useCardAnimation({ animationType, itemCount: childrenArray.length, useIndividualTriggers: true });
return ( return (
<section <div className={`card-list ${className}`}>
aria-label={ariaLabel} {items.map((item, index) => (
className={cls( <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="card-list-item">
"relative py-20 w-full", {item.title && <h3>{item.title}</h3>}
useInvertedBackground && "bg-foreground", {item.description && <p>{item.description}</p>}
className
)}
>
<div className={cls("w-content-width mx-auto flex flex-col gap-8", containerClassName)}>
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
<div className="flex flex-col gap-6">
{childrenArray.map((child, index) => (
<div
key={index}
ref={(el) => { itemRefs.current[index] = el; }}
className={cls(!disableCardWrapper && "card", !disableCardWrapper && (useUncappedRounding ? "rounded-theme" : "rounded-theme-capped"), cardClassName)}
>
{child}
</div>
))}
</div> </div>
</div> ))}
</section> </div>
); );
}; };
CardList.displayName = "CardList"; export default CardList;
export default memo(CardList);

View File

@@ -1,229 +1,20 @@
"use client"; 'use client';
import { memo, Children } from "react"; import React from 'react';
import { CardStackProps } from "./types"; import TimelineBase from './layouts/timelines/TimelineBase';
import GridLayout from "./layouts/grid/GridLayout"; import { CardStackItemShape } from '@/components/cardStack/types';
import AutoCarousel from "./layouts/carousels/AutoCarousel";
import ButtonCarousel from "./layouts/carousels/ButtonCarousel";
import TimelineBase from "./layouts/timelines/TimelineBase";
import { gridConfigs } from "./layouts/grid/gridConfigs";
const CardStack = ({ interface CardStackProps {
children, items: CardStackItemShape[];
mode = "buttons", className?: string;
gridVariant = "uniform-all-items-equal", }
uniformGridCustomHeightClasses,
gridRowsClassName,
itemHeightClassesOverride,
animationType,
supports3DAnimation = false,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout = "default",
useInvertedBackground,
carouselThreshold = 5,
bottomContent,
className = "",
containerClassName = "",
gridClassName = "",
carouselClassName = "",
carouselItemClassName = "",
controlsClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel = "Card stack",
}: CardStackProps) => {
const childrenArray = Children.toArray(children);
const itemCount = childrenArray.length;
// Check if the current grid config has gridRows defined const CardStack: React.FC<CardStackProps> = ({ items, className = '' }) => {
const gridConfig = gridConfigs[gridVariant]?.[itemCount]; return (
const hasFixedGridRows = gridConfig && 'gridRows' in gridConfig && gridConfig.gridRows; <div className={`card-stack ${className}`}>
<TimelineBase items={items} />
// If grid has fixed row heights and we have uniformGridCustomHeightClasses, </div>
// we need to use min-h-0 on md+ to prevent conflicts );
let adjustedHeightClasses = uniformGridCustomHeightClasses;
if (hasFixedGridRows && uniformGridCustomHeightClasses) {
// Extract the mobile min-height and add md:min-h-0
const mobileMinHeight = uniformGridCustomHeightClasses.split(' ')[0];
adjustedHeightClasses = `${mobileMinHeight} md:min-h-0`;
}
// Timeline layout for zigzag pattern (works best with 3-6 items)
if (gridVariant === "timeline" && itemCount >= 3 && itemCount <= 6) {
// Convert depth-3d to scale-rotate for timeline (doesn't support 3D)
const timelineAnimationType = animationType === "depth-3d" ? "scale-rotate" : animationType;
return (
<TimelineBase
variant={gridVariant}
uniformGridCustomHeightClasses={adjustedHeightClasses}
animationType={timelineAnimationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
className={className}
containerClassName={containerClassName}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
ariaLabel={ariaLabel}
>
{childrenArray}
</TimelineBase>
);
}
// Use grid for items below threshold, carousel for items at or above threshold
// Timeline with 7+ items will also use carousel
const useCarousel = itemCount >= carouselThreshold || (gridVariant === "timeline" && itemCount > 6);
// Grid layout for 1-4 items
if (!useCarousel) {
return (
<GridLayout
itemCount={itemCount}
gridVariant={gridVariant}
uniformGridCustomHeightClasses={adjustedHeightClasses}
gridRowsClassName={gridRowsClassName}
itemHeightClassesOverride={itemHeightClassesOverride}
animationType={animationType}
supports3DAnimation={supports3DAnimation}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
bottomContent={bottomContent}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
ariaLabel={ariaLabel}
>
{childrenArray}
</GridLayout>
);
}
// Auto-scroll carousel for 5+ items
if (mode === "auto") {
// Convert depth-3d to scale-rotate for carousel (doesn't support 3D)
const carouselAnimationType = animationType === "depth-3d" ? "scale-rotate" : animationType;
return (
<AutoCarousel
uniformGridCustomHeightClasses={adjustedHeightClasses}
animationType={carouselAnimationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
bottomContent={bottomContent}
className={className}
containerClassName={containerClassName}
carouselClassName={carouselClassName}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
ariaLabel={ariaLabel}
>
{childrenArray}
</AutoCarousel>
);
}
// Button-controlled carousel for 5+ items
// Convert depth-3d to scale-rotate for carousel (doesn't support 3D)
const carouselAnimationType = animationType === "depth-3d" ? "scale-rotate" : animationType;
return (
<ButtonCarousel
uniformGridCustomHeightClasses={adjustedHeightClasses}
animationType={carouselAnimationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
bottomContent={bottomContent}
className={className}
containerClassName={containerClassName}
carouselClassName={carouselClassName}
carouselItemClassName={carouselItemClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
ariaLabel={ariaLabel}
>
{childrenArray}
</ButtonCarousel>
);
}; };
CardStack.displayName = "CardStack"; export default CardStack;
export default memo(CardStack);

View File

@@ -1,92 +1,15 @@
"use client"; 'use client';
import { memo, useMemo } from "react"; import React from 'react';
import TextBox from "@/components/Textbox"; import { TextBoxProps } from '@/components/cardStack/types';
import { cls } from "@/lib/utils";
import type { TextBoxProps } from "./types";
const CardStackTextBox = ({ const CardStackTextBox: React.FC<TextBoxProps> = ({ title, description, className = '' }) => {
title, return (
titleSegments, <div className={`card-stack-textbox ${className}`}>
description, <h2>{title}</h2>
tag, <p>{description}</p>
tagIcon, </div>
tagAnimation, );
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
}: TextBoxProps) => {
const styles = useMemo(() => {
if (textboxLayout === "default") {
return {
className: cls("flex flex-col gap-3 md:gap-2", textBoxClassName),
titleClassName: cls("text-6xl font-medium text-center", titleClassName),
descriptionClassName: cls("text-lg leading-tight text-center md:max-w-6/10", descriptionClassName),
tagClassName: cls("w-fit px-3 py-1 text-sm rounded-theme card text-foreground inline-flex items-center gap-2 mb-0 mx-auto", tagClassName),
buttonContainerClassName: cls("flex flex-wrap gap-4 max-md:justify-center mt-1 md:mt-3 justify-center", buttonContainerClassName),
center: true,
};
}
if (textboxLayout === "inline-image") {
return {
className: cls("flex flex-col gap-3 md:gap-2", textBoxClassName),
titleClassName: cls("text-4xl md:text-5xl font-medium text-center", titleClassName),
descriptionClassName: cls("text-lg leading-tight text-center", descriptionClassName),
tagClassName: cls("w-fit px-3 py-1 text-sm rounded-theme card text-foreground inline-flex items-center gap-2 mb-0 mx-auto", tagClassName),
buttonContainerClassName: cls("flex flex-wrap gap-4 max-md:justify-center mt-1 md:mt-3 justify-center", buttonContainerClassName),
center: true,
};
}
return {
className: textBoxClassName,
titleClassName: cls("text-6xl font-medium", titleClassName),
descriptionClassName: cls("text-lg leading-tight", descriptionClassName),
tagClassName: cls("px-3 py-1 text-sm rounded-theme card text-foreground inline-flex items-center gap-2", tagClassName),
buttonContainerClassName: cls("flex flex-wrap gap-4 max-md:justify-center", buttonContainerClassName),
center: false,
};
}, [textboxLayout, textBoxClassName, titleClassName, descriptionClassName, tagClassName, buttonContainerClassName]);
if (!title && !titleSegments && !description) return null;
return (
<TextBox
title={title!}
titleSegments={titleSegments}
description={description!}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
className={styles.className}
titleClassName={styles.titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={styles.descriptionClassName}
tagClassName={styles.tagClassName}
buttonContainerClassName={styles.buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
center={styles.center}
/>
);
}; };
CardStackTextBox.displayName = "CardStackTextBox"; export default CardStackTextBox;
export default memo(CardStackTextBox);

View File

@@ -1,187 +1,35 @@
import { useRef } from "react"; 'use client';
import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import type { CardAnimationType, GridVariant } from "../types";
import { useDepth3DAnimation } from "./useDepth3DAnimation";
gsap.registerPlugin(ScrollTrigger); import { useEffect, useRef, useState } from 'react';
import { UseCardAnimationReturn } from '@/components/cardStack/types';
interface UseCardAnimationProps { export function useCardAnimation(): UseCardAnimationReturn {
animationType: CardAnimationType | "depth-3d"; const [isActive, setIsActive] = useState(false);
itemCount: number; const [isMobile, setIsMobile] = useState(false);
isGrid?: boolean; const itemRefsArray = useRef<(HTMLElement | null)[]>([]);
supports3DAnimation?: boolean; const containerRef = useRef<HTMLElement>(null);
gridVariant?: GridVariant; const perspectiveRef = useRef<HTMLElement>(null);
useIndividualTriggers?: boolean; const bottomContentRef = useRef<HTMLElement>(null);
}
export const useCardAnimation = ({ useEffect(() => {
animationType, const checkMobile = () => {
itemCount, setIsMobile(window.innerWidth < 768);
isGrid = true, };
supports3DAnimation = false, checkMobile();
gridVariant, window.addEventListener('resize', checkMobile);
useIndividualTriggers = false return () => window.removeEventListener('resize', checkMobile);
}: UseCardAnimationProps) => { }, []);
const itemRefs = useRef<(HTMLElement | null)[]>([]);
const containerRef = useRef<HTMLDivElement | null>(null);
const perspectiveRef = useRef<HTMLDivElement | null>(null);
const bottomContentRef = useRef<HTMLDivElement | null>(null);
// Enable 3D effect only when explicitly supported and conditions are met const itemRefs = itemRefsArray.current.map((el) => ({
const { isMobile } = useDepth3DAnimation({ current: el,
})) as React.RefObject<HTMLElement>[];
return {
isActive,
isMobile,
itemRefs, itemRefs,
containerRef, containerRef,
perspectiveRef, perspectiveRef,
isEnabled: animationType === "depth-3d" && isGrid && supports3DAnimation && gridVariant === "uniform-all-items-equal", bottomContentRef,
}); };
}
// Use scale-rotate as fallback when depth-3d conditions aren't met
const effectiveAnimationType =
animationType === "depth-3d" && (isMobile || !isGrid || gridVariant !== "uniform-all-items-equal")
? "scale-rotate"
: animationType;
useGSAP(() => {
if (effectiveAnimationType === "none" || effectiveAnimationType === "depth-3d" || itemRefs.current.length === 0) return;
const items = itemRefs.current.filter((el) => el !== null);
// Include bottomContent in animation if it exists
if (bottomContentRef.current) {
items.push(bottomContentRef.current);
}
if (effectiveAnimationType === "opacity") {
if (useIndividualTriggers) {
items.forEach((item) => {
gsap.fromTo(
item,
{ opacity: 0 },
{
opacity: 1,
duration: 1.25,
ease: "sine",
scrollTrigger: {
trigger: item,
start: "top 80%",
toggleActions: "play none none none",
},
}
);
});
} else {
gsap.fromTo(
items,
{ opacity: 0 },
{
opacity: 1,
duration: 1.25,
stagger: 0.15,
ease: "sine",
scrollTrigger: {
trigger: items[0],
start: "top 80%",
toggleActions: "play none none none",
},
}
);
}
} else if (effectiveAnimationType === "slide-up") {
items.forEach((item, index) => {
gsap.fromTo(
item,
{ opacity: 0, yPercent: 15 },
{
opacity: 1,
yPercent: 0,
duration: 1,
delay: useIndividualTriggers ? 0 : index * 0.15,
ease: "sine",
scrollTrigger: {
trigger: useIndividualTriggers ? item : items[0],
start: "top 80%",
toggleActions: "play none none none",
},
}
);
});
} else if (effectiveAnimationType === "scale-rotate") {
if (useIndividualTriggers) {
items.forEach((item) => {
gsap.fromTo(
item,
{ scaleX: 0, rotate: 10 },
{
scaleX: 1,
rotate: 0,
duration: 1,
ease: "power3",
scrollTrigger: {
trigger: item,
start: "top 80%",
toggleActions: "play none none none",
},
}
);
});
} else {
gsap.fromTo(
items,
{ scaleX: 0, rotate: 10 },
{
scaleX: 1,
rotate: 0,
duration: 1,
stagger: 0.15,
ease: "power3",
scrollTrigger: {
trigger: items[0],
start: "top 80%",
toggleActions: "play none none none",
},
}
);
}
} else if (effectiveAnimationType === "blur-reveal") {
if (useIndividualTriggers) {
items.forEach((item) => {
gsap.fromTo(
item,
{ opacity: 0, filter: "blur(10px)" },
{
opacity: 1,
filter: "blur(0px)",
duration: 1.2,
ease: "power2.out",
scrollTrigger: {
trigger: item,
start: "top 80%",
toggleActions: "play none none none",
},
}
);
});
} else {
gsap.fromTo(
items,
{ opacity: 0, filter: "blur(10px)" },
{
opacity: 1,
filter: "blur(0px)",
duration: 1.2,
stagger: 0.15,
ease: "power2.out",
scrollTrigger: {
trigger: items[0],
start: "top 80%",
toggleActions: "play none none none",
},
}
);
}
}
}, [effectiveAnimationType, itemCount, useIndividualTriggers]);
return { itemRefs, containerRef, perspectiveRef, bottomContentRef };
};

View File

@@ -1,118 +1,25 @@
import { useEffect, useState, useRef, RefObject } from "react"; 'use client';
const MOBILE_BREAKPOINT = 768; import { useEffect, useState } from 'react';
const ANIMATION_SPEED = 0.05;
const ROTATION_SPEED = 0.1;
const MOUSE_MULTIPLIER = 0.5;
const ROTATION_MULTIPLIER = 0.25;
interface UseDepth3DAnimationProps { export const useDepth3DAnimation = (elementRef: React.RefObject<HTMLElement>) => {
itemRefs: RefObject<(HTMLElement | null)[]>; const [isActive, setIsActive] = useState(false);
containerRef: RefObject<HTMLDivElement | null>;
perspectiveRef?: RefObject<HTMLDivElement | null>;
isEnabled: boolean;
}
export const useDepth3DAnimation = ({
itemRefs,
containerRef,
perspectiveRef,
isEnabled,
}: UseDepth3DAnimationProps) => {
const [isMobile, setIsMobile] = useState(false);
// Detect mobile viewport
useEffect(() => { useEffect(() => {
const checkMobile = () => { if (!elementRef.current) return;
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
checkMobile(); const handleMouseEnter = () => setIsActive(true);
window.addEventListener("resize", checkMobile); const handleMouseLeave = () => setIsActive(false);
const element = elementRef.current;
element.addEventListener('mouseenter', handleMouseEnter);
element.addEventListener('mouseleave', handleMouseLeave);
return () => { return () => {
window.removeEventListener("resize", checkMobile); element.removeEventListener('mouseenter', handleMouseEnter);
element.removeEventListener('mouseleave', handleMouseLeave);
}; };
}, []); }, [elementRef]);
// 3D mouse-tracking effect (desktop only) return { isActive };
useEffect(() => {
if (!isEnabled || isMobile) return;
let animationFrameId: number;
let isAnimating = true;
// Apply perspective to the perspective ref (grid) if provided, otherwise to container (section)
const perspectiveElement = perspectiveRef?.current || containerRef.current;
if (perspectiveElement) {
perspectiveElement.style.perspective = "1200px";
perspectiveElement.style.transformStyle = "preserve-3d";
}
let mouseX = 0;
let mouseY = 0;
let isMouseInSection = false;
let currentX = 0;
let currentY = 0;
let currentRotationX = 0;
let currentRotationY = 0;
const handleMouseMove = (event: MouseEvent): void => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
isMouseInSection =
event.clientX >= rect.left &&
event.clientX <= rect.right &&
event.clientY >= rect.top &&
event.clientY <= rect.bottom;
}
if (isMouseInSection) {
mouseX = (event.clientX / window.innerWidth) * 100 - 50;
mouseY = (event.clientY / window.innerHeight) * 100 - 50;
}
};
const animate = (): void => {
if (!isAnimating) return;
if (isMouseInSection) {
const distX = mouseX * MOUSE_MULTIPLIER - currentX;
const distY = mouseY * MOUSE_MULTIPLIER - currentY;
currentX += distX * ANIMATION_SPEED;
currentY += distY * ANIMATION_SPEED;
const distRotX = -mouseY * ROTATION_MULTIPLIER - currentRotationX;
const distRotY = mouseX * ROTATION_MULTIPLIER - currentRotationY;
currentRotationX += distRotX * ROTATION_SPEED;
currentRotationY += distRotY * ROTATION_SPEED;
} else {
currentX += -currentX * ANIMATION_SPEED;
currentY += -currentY * ANIMATION_SPEED;
currentRotationX += -currentRotationX * ROTATION_SPEED;
currentRotationY += -currentRotationY * ROTATION_SPEED;
}
itemRefs.current?.forEach((ref) => {
if (!ref) return;
ref.style.transform = `translate(${currentX}px, ${currentY}px) rotateX(${currentRotationX}deg) rotateY(${currentRotationY}deg)`;
});
animationFrameId = requestAnimationFrame(animate);
};
animate();
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
isAnimating = false;
};
}, [isEnabled, isMobile, itemRefs, containerRef]);
return { isMobile };
}; };

View File

@@ -1,144 +1,18 @@
"use client"; 'use client';
import { memo, Children, useCallback, useEffect, useState } from "react"; import React from 'react';
import useEmblaCarousel from "embla-carousel-react"; import { ArrowCarouselProps } from '@/components/cardStack/types';
import { EmblaCarouselType } from "embla-carousel";
import CardStackTextBox from "../../CardStackTextBox";
import { cls } from "@/lib/utils";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { ArrowCarouselProps } from "../../types";
const ArrowCarousel = ({ const ArrowCarousel: React.FC<ArrowCarouselProps> = ({ items, className = '' }) => {
children, return (
title, <div className={`arrow-carousel ${className}`}>
titleSegments, {items.map((item, index) => (
description, <div key={item.id || index} className="carousel-item">
tag, {item.title}
tagIcon, </div>
tagAnimation, ))}
buttons, </div>
buttonAnimation, );
textboxLayout = "default",
useInvertedBackground,
className = "",
containerClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel = "Carousel section",
}: ArrowCarouselProps) => {
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true, align: "center" });
const [selectedIndex, setSelectedIndex] = useState(0);
const childrenArray = Children.toArray(children);
const onSelect = useCallback((emblaApi: EmblaCarouselType) => {
setSelectedIndex(emblaApi.selectedScrollSnap());
}, []);
const scrollPrev = useCallback(() => emblaApi?.scrollPrev(), [emblaApi]);
const scrollNext = useCallback(() => emblaApi?.scrollNext(), [emblaApi]);
useEffect(() => {
if (!emblaApi) return;
onSelect(emblaApi);
emblaApi.on("select", onSelect).on("reInit", onSelect);
return () => {
emblaApi.off("select", onSelect).off("reInit", onSelect);
};
}, [emblaApi, onSelect]);
return (
<section
className={cls(
"relative py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-full mx-auto flex flex-col gap-6", containerClassName)}>
<div className="w-content-width mx-auto">
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
</div>
<div className="relative w-full">
<div
className={cls(
"overflow-hidden w-full relative z-10 mask-fade-x",
carouselClassName
)}
ref={emblaRef}
>
<div className="flex w-full">
{childrenArray.map((child, index) => (
<div
key={index}
className="flex-none w-60 md:w-40 mr-6"
>
<div className={cls(
"transition-all duration-500 ease-out",
selectedIndex === index ? "opacity-100 scale-100" : "opacity-70 scale-90"
)}>
{child}
</div>
</div>
))}
</div>
</div>
<div className={cls("absolute inset-y-0 w-content-width mx-auto left-0 right-0 flex items-center justify-between pointer-events-none z-10", controlsClassName)}>
<button
onClick={scrollPrev}
className="pointer-events-auto primary-button h-8 w-auto aspect-square rounded-theme flex items-center justify-center cursor-pointer"
aria-label="Previous slide"
>
<ChevronLeft className="w-4/10 h-4/10 text-primary-cta-text" />
</button>
<button
onClick={scrollNext}
className="pointer-events-auto primary-button h-8 w-auto aspect-square rounded-theme flex items-center justify-center cursor-pointer"
aria-label="Next slide"
>
<ChevronRight className="w-4/10 h-4/10 text-primary-cta-text" />
</button>
</div>
</div>
</div>
</section>
);
}; };
ArrowCarousel.displayName = "ArrowCarousel"; export default ArrowCarousel;
export default memo(ArrowCarousel);

View File

@@ -1,148 +1,22 @@
"use client"; 'use client';
import { memo, Children } from "react"; import React from 'react';
import Marquee from "react-fast-marquee"; import { AutoCarouselProps } from '@/components/cardStack/types';
import CardStackTextBox from "../../CardStackTextBox"; import { useCardAnimation } from '@/components/cardStack/hooks/useCardAnimation';
import { cls } from "@/lib/utils";
import { AutoCarouselProps } from "../../types";
import { useCardAnimation } from "../../hooks/useCardAnimation";
const AutoCarousel = ({ const AutoCarousel: React.FC<AutoCarouselProps> = ({ items, className = '' }) => {
children, const animation = useCardAnimation();
uniformGridCustomHeightClasses, const itemRefs = React.useRef<(HTMLDivElement | null)[]>([]);
animationType,
speed = 50,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout = "default",
useInvertedBackground,
bottomContent,
className = "",
containerClassName = "",
carouselClassName = "",
itemClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel,
showTextBox = true,
dualMarquee = false,
topMarqueeDirection = "left",
bottomCarouselClassName = "",
marqueeGapClassName = "",
}: AutoCarouselProps) => {
const childrenArray = Children.toArray(children);
const heightClasses = uniformGridCustomHeightClasses || "min-h-80 2xl:min-h-90";
const { itemRefs, bottomContentRef } = useCardAnimation({
animationType,
itemCount: childrenArray.length,
isGrid: false
});
// Bottom marquee direction is opposite of top return (
const bottomMarqueeDirection = topMarqueeDirection === "left" ? "right" : "left"; <div ref={animation.bottomContentRef as React.Ref<HTMLDivElement>} className={`auto-carousel ${className}`}>
{items.map((item, index) => (
// Reverse order for bottom marquee to avoid alignment with top <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="carousel-item">
const bottomChildren = dualMarquee ? [...childrenArray].reverse() : []; {item.title}
</div>
return ( ))}
<section </div>
className={cls( );
"relative py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
aria-live="off"
>
<div className={cls("w-full md:w-content-width mx-auto", containerClassName)}>
<div className="w-full flex flex-col items-center">
<div className="w-full flex flex-col gap-6">
{showTextBox && (title || titleSegments || description) && (
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
)}
<div
className={cls(
"w-full flex flex-col",
marqueeGapClassName || "gap-6"
)}
>
{/* Top/Single Marquee */}
<div className={cls("overflow-hidden w-full relative z-10 mask-padding-x", carouselClassName)}>
<Marquee gradient={false} speed={speed} direction={topMarqueeDirection}>
{Children.map(childrenArray, (child, index) => (
<div
key={index}
className={cls("flex-none w-carousel-item-3 xl:w-carousel-item-4 mb-1 mr-6", heightClasses, itemClassName)}
ref={(el) => { itemRefs.current[index] = el; }}
>
{child}
</div>
))}
</Marquee>
</div>
{/* Bottom Marquee (only if dualMarquee is true) - Reversed order, opposite direction */}
{dualMarquee && (
<div className={cls("overflow-hidden w-full relative z-10 mask-padding-x", bottomCarouselClassName || carouselClassName)}>
<Marquee gradient={false} speed={speed} direction={bottomMarqueeDirection}>
{Children.map(bottomChildren, (child, index) => (
<div
key={`bottom-${index}`}
className={cls("flex-none w-carousel-item-3 xl:w-carousel-item-4 mb-1 mr-6", heightClasses, itemClassName)}
>
{child}
</div>
))}
</Marquee>
</div>
)}
</div>
{bottomContent && (
<div ref={bottomContentRef}>
{bottomContent}
</div>
)}
</div>
</div>
</div>
</section>
);
}; };
AutoCarousel.displayName = "AutoCarousel"; export default AutoCarousel;
export default memo(AutoCarousel);

View File

@@ -1,182 +1,22 @@
"use client"; 'use client';
import { memo, Children } from "react"; import React from 'react';
import useEmblaCarousel from "embla-carousel-react"; import { ButtonCarouselProps } from '@/components/cardStack/types';
import { ChevronLeft, ChevronRight } from "lucide-react"; import { useCardAnimation } from '@/components/cardStack/hooks/useCardAnimation';
import CardStackTextBox from "../../CardStackTextBox";
import { cls } from "@/lib/utils";
import { ButtonCarouselProps } from "../../types";
import { usePrevNextButtons } from "../../hooks/usePrevNextButtons";
import { useScrollProgress } from "../../hooks/useScrollProgress";
import { useCardAnimation } from "../../hooks/useCardAnimation";
const ButtonCarousel = ({ const ButtonCarousel: React.FC<ButtonCarouselProps> = ({ items, className = '' }) => {
children, const animation = useCardAnimation();
uniformGridCustomHeightClasses, const itemRefs = React.useRef<(HTMLDivElement | null)[]>([]);
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout = "default",
useInvertedBackground,
bottomContent,
className = "",
containerClassName = "",
carouselClassName = "",
carouselItemClassName = "",
controlsClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel,
}: ButtonCarouselProps) => {
const [emblaRef, emblaApi] = useEmblaCarousel({ dragFree: true });
const { return (
prevBtnDisabled, <div ref={animation.bottomContentRef as React.Ref<HTMLDivElement>} className={`button-carousel ${className}`}>
nextBtnDisabled, {items.map((item, index) => (
onPrevButtonClick, <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="carousel-item">
onNextButtonClick, {item.title}
} = usePrevNextButtons(emblaApi); </div>
))}
const scrollProgress = useScrollProgress(emblaApi); </div>
);
const childrenArray = Children.toArray(children);
const heightClasses = uniformGridCustomHeightClasses || "min-h-80 2xl:min-h-90";
const { itemRefs, bottomContentRef } = useCardAnimation({
animationType,
itemCount: childrenArray.length,
isGrid: false
});
return (
<section
className={cls(
"relative px-[var(--width-0)] py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-full mx-auto", containerClassName)}>
<div className="w-full flex flex-col items-center">
<div className="w-full flex flex-col gap-6">
{(title || titleSegments || description) && (
<div className="w-content-width mx-auto">
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
</div>
)}
<div
className={cls(
"w-full flex flex-col gap-6"
)}
>
<div
className={cls(
"overflow-hidden w-full relative z-10 flex cursor-grab",
carouselClassName
)}
ref={emblaRef}
>
<div className="flex gap-6 w-full">
<div className="flex-shrink-0 w-carousel-padding" />
{Children.map(childrenArray, (child, index) => (
<div
key={index}
className={cls("flex-none select-none w-carousel-item-3 xl:w-carousel-item-4 mb-6", heightClasses, carouselItemClassName)}
ref={(el) => { itemRefs.current[index] = el; }}
>
{child}
</div>
))}
<div className="flex-shrink-0 w-carousel-padding" />
</div>
</div>
<div className={cls("w-full flex", controlsClassName)}>
<div className="flex-shrink-0 w-carousel-padding-controls" />
<div className="flex justify-between items-center w-full">
<div
className="rounded-theme card relative h-2 w-50 overflow-hidden"
role="progressbar"
aria-label="Carousel progress"
aria-valuenow={Math.round(scrollProgress)}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className="bg-foreground primary-button absolute! w-full top-0 bottom-0 -left-full rounded-theme"
style={{ transform: `translate3d(${scrollProgress}%,0px,0px)` }}
/>
</div>
<div className="flex items-center gap-3">
<button
onClick={onPrevButtonClick}
disabled={prevBtnDisabled}
className="secondary-button h-8 aspect-square flex items-center justify-center rounded-theme cursor-pointer transition-colors disabled:cursor-not-allowed disabled:opacity-50"
type="button"
aria-label="Previous slide"
>
<ChevronLeft className="h-[40%] w-auto aspect-square text-secondary-cta-text" />
</button>
<button
onClick={onNextButtonClick}
disabled={nextBtnDisabled}
className="secondary-button h-8 aspect-square flex items-center justify-center rounded-theme cursor-pointer transition-colors disabled:cursor-not-allowed disabled:opacity-50"
type="button"
aria-label="Next slide"
>
<ChevronRight className="h-[40%] w-auto aspect-square text-secondary-cta-text" />
</button>
</div>
</div>
<div className="flex-shrink-0 w-carousel-padding-controls" />
</div>
</div>
{bottomContent && (
<div ref={bottomContentRef} className="w-content-width mx-auto">
{bottomContent}
</div>
)}
</div>
</div>
</div>
</section>
);
}; };
ButtonCarousel.displayName = "ButtonCarousel"; export default ButtonCarousel;
export default memo(ButtonCarousel);

View File

@@ -1,155 +1,18 @@
"use client"; 'use client';
import { memo, Children, cloneElement, isValidElement, useCallback, useEffect, useState } from "react"; import React from 'react';
import useEmblaCarousel from "embla-carousel-react"; import { FullWidthCarouselProps } from '@/components/cardStack/types';
import { EmblaCarouselType } from "embla-carousel";
import CardStackTextBox from "../../CardStackTextBox";
import { cls } from "@/lib/utils";
import { FullWidthCarouselProps } from "../../types";
const FullWidthCarousel = ({ const FullWidthCarousel: React.FC<FullWidthCarouselProps> = ({ items, className = '' }) => {
children, return (
title, <div className={`full-width-carousel ${className}`}>
titleSegments, {items.map((item, index) => (
description, <div key={item.id || index} className="carousel-item">
tag, {item.title}
tagIcon, </div>
tagAnimation, ))}
buttons, </div>
buttonAnimation, );
textboxLayout = "default",
useInvertedBackground,
className = "",
containerClassName = "",
carouselClassName = "",
dotsClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel = "Carousel section",
}: FullWidthCarouselProps) => {
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true, align: "center" });
const [selectedIndex, setSelectedIndex] = useState(0);
const childrenArray = Children.toArray(children);
const onSelect = useCallback((emblaApi: EmblaCarouselType) => {
setSelectedIndex(emblaApi.selectedScrollSnap());
}, []);
const scrollTo = useCallback(
(index: number) => {
if (!emblaApi) return;
emblaApi.scrollTo(index);
},
[emblaApi]
);
useEffect(() => {
if (!emblaApi) return;
onSelect(emblaApi);
emblaApi.on("select", onSelect).on("reInit", onSelect);
return () => {
emblaApi.off("select", onSelect).off("reInit", onSelect);
};
}, [emblaApi, onSelect]);
useEffect(() => {
if (!emblaApi) return;
const autoplay = setInterval(() => {
emblaApi.scrollNext();
}, 5000);
return () => clearInterval(autoplay);
}, [emblaApi]);
return (
<section
className={cls(
"relative py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-full mx-auto flex flex-col gap-6", containerClassName)}>
<div className="w-content-width mx-auto">
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
</div>
<div className="w-full">
<div
className={cls(
"overflow-hidden w-full relative z-10",
carouselClassName
)}
ref={emblaRef}
>
<div className="flex w-full">
{Children.map(childrenArray, (child, index) => (
<div
key={index}
className="flex-none w-70 mr-6"
>
{isValidElement(child)
? cloneElement(child, { isActive: selectedIndex === index } as Record<string, unknown>)
: child}
</div>
))}
</div>
</div>
</div>
<div className={cls("flex items-center justify-center gap-2", dotsClassName)}>
{childrenArray.map((_, index) => (
<button
key={index}
type="button"
onClick={() => scrollTo(index)}
className={cls(
"relative cursor-pointer h-2 rounded-theme bg-accent transition-all duration-300",
selectedIndex === index
? "w-8 opacity-100"
: "w-2 opacity-20"
)}
aria-label={`Go to slide ${index + 1}`}
aria-current={selectedIndex === index}
/>
))}
</div>
</div>
</section>
);
}; };
FullWidthCarousel.displayName = "FullWidthCarousel"; export default FullWidthCarousel;
export default memo(FullWidthCarousel);

View File

@@ -1,150 +1,26 @@
"use client"; 'use client';
import { memo, Children } from "react"; import React from 'react';
import CardStackTextBox from "../../CardStackTextBox"; import { GridLayoutProps } from '@/components/cardStack/types';
import { cls } from "@/lib/utils"; import { useCardAnimation } from '@/components/cardStack/hooks/useCardAnimation';
import { GridLayoutProps } from "../../types";
import { gridConfigs } from "./gridConfigs";
import { useCardAnimation } from "../../hooks/useCardAnimation";
const GridLayout = ({ const GridLayout: React.FC<GridLayoutProps> = ({ items, className = '' }) => {
children, const animation = useCardAnimation();
itemCount, const itemRefs = React.useRef<(HTMLDivElement | null)[]>([]);
gridVariant = "uniform-all-items-equal",
uniformGridCustomHeightClasses,
gridRowsClassName,
itemHeightClassesOverride,
animationType,
supports3DAnimation = false,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout = "default",
useInvertedBackground,
bottomContent,
className = "",
containerClassName = "",
gridClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel,
}: GridLayoutProps) => {
// Get config for this variant and item count
const config = gridConfigs[gridVariant]?.[itemCount];
// Fallback to default uniform grid if no config return (
const gridColsMap = { <div ref={animation.containerRef as React.Ref<HTMLDivElement>} className={`grid-layout ${className}`}>
1: "md:grid-cols-1", <div ref={animation.perspectiveRef as React.Ref<HTMLDivElement>} className="grid-perspective">
2: "md:grid-cols-2", <div ref={animation.bottomContentRef as React.Ref<HTMLDivElement>} className="grid-container">
3: "md:grid-cols-3", {items.map((item, index) => (
4: "md:grid-cols-4", <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="grid-item">
}; {item.title}
const defaultGridCols = gridColsMap[itemCount as keyof typeof gridColsMap] || "md:grid-cols-4";
// Use config values or fallback
const gridCols = config?.gridCols || defaultGridCols;
const gridRows = gridRowsClassName || config?.gridRows || "";
const itemClasses = config?.itemClasses || [];
const itemHeightClasses = itemHeightClassesOverride || config?.itemHeightClasses || [];
const heightClasses = uniformGridCustomHeightClasses || config?.heightClasses || "";
const itemWrapperClass = config?.itemWrapperClass || "";
const childrenArray = Children.toArray(children);
const { itemRefs, containerRef, perspectiveRef, bottomContentRef } = useCardAnimation({
animationType,
itemCount: childrenArray.length,
isGrid: true,
supports3DAnimation,
gridVariant
});
return (
<section
ref={containerRef}
className={cls(
"relative py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-content-width mx-auto flex flex-col gap-6", containerClassName)}>
{(title || titleSegments || description) && (
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
)}
<div
ref={perspectiveRef}
className={cls(
"grid grid-cols-1 gap-6",
gridCols,
gridRows,
gridClassName
)}
>
{childrenArray.map((child, index) => {
const itemClass = itemClasses[index] || "";
const itemHeightClass = itemHeightClasses[index] || "";
const combinedClass = cls(itemWrapperClass, itemClass, itemHeightClass, heightClasses);
return combinedClass ? (
<div
key={index}
className={combinedClass}
ref={(el) => { itemRefs.current[index] = el; }}
>
{child}
</div>
) : (
<div
key={index}
ref={(el) => { itemRefs.current[index] = el; }}
>
{child}
</div>
);
})}
</div>
{bottomContent && (
<div ref={bottomContentRef}>
{bottomContent}
</div>
)}
</div> </div>
</section> ))}
); </div>
</div>
</div>
);
}; };
GridLayout.displayName = "GridLayout"; export default GridLayout;
export default memo(GridLayout);

View File

@@ -1,149 +1,26 @@
"use client"; 'use client';
import React, { Children, useCallback } from "react"; import React, { useRef } from 'react';
import { cls } from "@/lib/utils"; import { CardStackItemShape } from '@/components/cardStack/types';
import CardStackTextBox from "../../CardStackTextBox";
import { useCardAnimation } from "../../hooks/useCardAnimation";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, CardAnimationType, TitleSegment, ButtonAnimationType } from "../../types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type TimelineVariant = "timeline";
interface TimelineBaseProps { interface TimelineBaseProps {
children: React.ReactNode; items: CardStackItemShape[];
variant?: TimelineVariant;
uniformGridCustomHeightClasses?: string;
animationType: CardAnimationType;
title?: string;
titleSegments?: TitleSegment[];
description?: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout?: TextboxLayout;
useInvertedBackground?: InvertedBackground;
className?: string; className?: string;
containerClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
ariaLabel?: string;
} }
const TimelineBase = ({ const TimelineBase: React.FC<TimelineBaseProps> = ({ items, className = '' }) => {
children, const containerRef = useRef<HTMLDivElement>(null);
variant = "timeline",
uniformGridCustomHeightClasses = "min-h-80 2xl:min-h-90",
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout = "default",
useInvertedBackground,
className = "",
containerClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel = "Timeline section",
}: TimelineBaseProps) => {
const childrenArray = Children.toArray(children);
const { itemRefs } = useCardAnimation({
animationType,
itemCount: childrenArray.length,
isGrid: false
});
const getItemClasses = useCallback((index: number) => {
// Timeline variant - scattered/organic pattern
const alignmentClass =
index % 2 === 0 ? "self-start ml-0" : "self-end mr-0";
const marginClasses = cls(
index % 4 === 0 && "md:ml-0",
index % 4 === 1 && "md:mr-20",
index % 4 === 2 && "md:ml-15",
index % 4 === 3 && "md:mr-30"
);
return cls(alignmentClass, marginClasses);
}, []);
return ( return (
<section <div ref={containerRef} className={`timeline-container ${className}`}>
className={cls( {items.map((item, index) => (
"relative py-20 w-full", <div key={item.id || index} className="timeline-item">
useInvertedBackground && "bg-foreground", <div className="timeline-marker" />
className <div className="timeline-content">{item.title}</div>
)}
aria-label={ariaLabel}
>
<div
className={cls("w-content-width mx-auto flex flex-col gap-6", containerClassName)}
>
{(title || titleSegments || description) && (
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
)}
<div
className={cls(
"relative z-10 flex flex-col gap-6 md:gap-15"
)}
>
{Children.map(childrenArray, (child, index) => (
<div
key={index}
className={cls("w-65 md:w-25", uniformGridCustomHeightClasses, getItemClasses(index))}
ref={(el) => { itemRefs.current[index] = el; }}
>
{child}
</div>
))}
</div> </div>
</div> ))}
</section> </div>
); );
}; };
TimelineBase.displayName = "TimelineBase"; export default TimelineBase;
export default React.memo(TimelineBase);

View File

@@ -1,147 +1,27 @@
"use client"; 'use client';
import React, { useEffect, useRef, memo, Children } from "react"; import React from 'react';
import { gsap } from "gsap"; import {
import { ScrollTrigger } from "gsap/ScrollTrigger"; ButtonConfig,
import CardStackTextBox from "../../CardStackTextBox"; ButtonAnimationType,
import { cls } from "@/lib/utils"; TitleSegment,
import type { LucideIcon } from "lucide-react"; } from '@/components/cardStack/types';
import type { ButtonConfig, ButtonAnimationType, TitleSegment } from "../../types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
gsap.registerPlugin(ScrollTrigger);
interface TimelineCardStackProps { interface TimelineCardStackProps {
children: React.ReactNode; items: any[];
title: string; className?: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground?: InvertedBackground;
className?: string;
containerClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
ariaLabel?: string;
} }
const TimelineCardStack = ({ const TimelineCardStack: React.FC<TimelineCardStackProps> = ({ items, className = '' }) => {
children, return (
title, <div className={`timeline-card-stack ${className}`}>
titleSegments, {items.map((item, index) => (
description, <div key={item.id || index} className="timeline-card">
tag, {item.title}
tagIcon, </div>
tagAnimation, ))}
buttons, </div>
buttonAnimation, );
textboxLayout,
useInvertedBackground,
className = "",
containerClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
ariaLabel = "Timeline section",
}: TimelineCardStackProps) => {
const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
const childrenArray = Children.toArray(children);
useEffect(() => {
const ctx = gsap.context(() => {
itemRefs.current.forEach((ref, position) => {
if (!ref) return;
const isLast = position === itemRefs.current.length - 1;
const timeline = gsap.timeline({
scrollTrigger: {
trigger: ref,
start: "center center",
end: "+=100%",
scrub: true,
},
});
timeline.set(ref, { willChange: "opacity" }).to(ref, {
ease: "none",
opacity: isLast ? 1 : 0,
});
});
});
return () => {
ctx.revert();
};
}, [childrenArray.length]);
return (
<section
className={cls(
"relative overflow-visible h-fit py-20 w-full",
useInvertedBackground && "bg-foreground",
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-content-width mx-auto flex flex-col gap-6", containerClassName)}>
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
<div className="w-full flex flex-col gap-[var(--width-25)] md:gap-[6.25vh]">
{Children.map(childrenArray, (child, index) => (
<div
key={index}
ref={(el) => {
itemRefs.current[index] = el;
}}
className="!sticky w-full card backdrop-blur-xs rounded-theme-capped h-[140vw] md:h-[75vh] top-[25vw] md:top-[12.5vh]"
>
{child}
</div>
))}
</div>
</div>
</section>
);
}; };
TimelineCardStack.displayName = "TimelineCardStack"; export default TimelineCardStack;
export default memo(TimelineCardStack);

View File

@@ -1,175 +1,29 @@
"use client"; 'use client';
import React, { Children, useCallback } from "react"; import React from 'react';
import { cls } from "@/lib/utils"; import {
import CardStackTextBox from "../../CardStackTextBox"; ButtonConfig,
import { useTimelineHorizontal, type MediaItem } from "../../hooks/useTimelineHorizontal"; ButtonAnimationType,
import MediaContent from "@/components/shared/MediaContent"; TitleSegment,
import type { LucideIcon } from "lucide-react"; TextboxLayout,
import type { ButtonConfig, ButtonAnimationType, TitleSegment, TextboxLayout, InvertedBackground } from "../../types"; InvertedBackground,
} from '@/components/cardStack/types';
interface TimelineHorizontalCardStackProps { interface TimelineHorizontalCardStackProps {
children: React.ReactNode; items: any[];
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground?: InvertedBackground;
mediaItems?: MediaItem[];
className?: string; className?: string;
containerClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
cardClassName?: string;
progressBarClassName?: string;
mediaContainerClassName?: string;
mediaClassName?: string;
ariaLabel?: string;
} }
const TimelineHorizontalCardStack = ({ const TimelineHorizontalCardStack: React.FC<TimelineHorizontalCardStackProps> = ({ items, className = '' }) => {
children,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
mediaItems,
className = "",
containerClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
cardClassName = "",
progressBarClassName = "",
mediaContainerClassName = "",
mediaClassName = "",
ariaLabel = "Timeline section",
}: TimelineHorizontalCardStackProps) => {
const childrenArray = Children.toArray(children);
const itemCount = childrenArray.length;
const { activeIndex, progressRefs, handleItemClick, imageOpacity, currentMediaSrc } = useTimelineHorizontal({
itemCount,
mediaItems,
});
const getGridColumns = useCallback(() => {
if (itemCount === 2) return "md:grid-cols-2";
if (itemCount === 3) return "md:grid-cols-3";
return "md:grid-cols-4";
}, [itemCount]);
const getItemOpacity = useCallback(
(index: number) => {
return index <= activeIndex ? "opacity-100" : "opacity-50";
},
[activeIndex]
);
return ( return (
<section <div className={`timeline-horizontal-card-stack ${className}`}>
className={cls( {items.map((item, index) => (
"relative py-20 w-full", <div key={item.id || index} className="timeline-horizontal-card">
useInvertedBackground && "bg-foreground", {item.title}
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-content-width mx-auto flex flex-col gap-6", containerClassName)}>
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
{mediaItems && mediaItems.length > 0 && (
<div className={cls("relative card rounded-theme-capped overflow-hidden aspect-square md:aspect-[17/9]", mediaContainerClassName)}>
<div
className="absolute inset-6 z-1 transition-opacity duration-300 overflow-hidden"
style={{ opacity: imageOpacity }}
>
<MediaContent
imageSrc={currentMediaSrc.imageSrc}
videoSrc={currentMediaSrc.videoSrc}
imageAlt={mediaItems[activeIndex]?.imageAlt}
videoAriaLabel={mediaItems[activeIndex]?.videoAriaLabel}
imageClassName={cls("w-full h-full object-cover", mediaClassName)}
/>
</div>
</div>
)}
<div className={cls("relative grid grid-cols-1 gap-6 md:gap-6", getGridColumns())}>
{Children.map(childrenArray, (child, index) => (
<div
key={index}
className={cls(
"card rounded-theme-capped p-6 flex flex-col justify-between gap-6 transition-all duration-300",
index === activeIndex ? "cursor-default" : "cursor-pointer hover:shadow-lg",
getItemOpacity(index),
cardClassName
)}
onClick={() => handleItemClick(index)}
>
{child}
<div className="relative w-full h-px overflow-hidden">
<div className="absolute z-0 w-full h-full bg-foreground/20" />
<div
ref={(el) => {
if (el !== null) {
progressRefs.current[index] = el;
}
}}
className={cls("absolute z-10 h-full w-full bg-foreground origin-left", progressBarClassName)}
style={{ transform: "scaleX(0)" }}
/>
</div>
</div>
))}
</div> </div>
</div> ))}
</section> </div>
); );
}; };
TimelineHorizontalCardStack.displayName = "TimelineHorizontalCardStack"; export default TimelineHorizontalCardStack;
export default React.memo(TimelineHorizontalCardStack);

View File

@@ -1,275 +1,30 @@
"use client"; 'use client';
import React, { memo } from "react"; import React from 'react';
import MediaContent from "@/components/shared/MediaContent"; import {
import CardStackTextBox from "../../CardStackTextBox"; ButtonConfig,
import { usePhoneAnimations, type TimelinePhoneViewItem } from "../../hooks/usePhoneAnimations"; ButtonAnimationType,
import { useCardAnimation } from "../../hooks/useCardAnimation"; TitleSegment,
import { cls } from "@/lib/utils"; CardAnimationType,
import type { LucideIcon } from "lucide-react"; } from '@/components/cardStack/types';
import type { ButtonConfig, ButtonAnimationType, TitleSegment, CardAnimationType } from "../../types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
interface PhoneFrameProps {
imageSrc?: string;
videoSrc?: string;
imageAlt?: string;
videoAriaLabel?: string;
phoneRef: (el: HTMLDivElement | null) => void;
className?: string;
}
const PhoneFrame = memo(({
imageSrc,
videoSrc,
imageAlt,
videoAriaLabel,
phoneRef,
className = "",
}: PhoneFrameProps) => (
<div
ref={phoneRef}
className={cls("card rounded-theme-capped p-1 overflow-hidden", className)}
>
<MediaContent
imageSrc={imageSrc}
videoSrc={videoSrc}
imageAlt={imageAlt}
videoAriaLabel={videoAriaLabel}
imageClassName="w-full h-full object-cover rounded-theme-capped"
/>
</div>
));
PhoneFrame.displayName = "PhoneFrame";
interface TimelinePhoneViewProps { interface TimelinePhoneViewProps {
items: TimelinePhoneViewItem[]; items: any[];
showTextBox?: boolean;
showDivider?: boolean;
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
animationType: CardAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground?: InvertedBackground;
className?: string; className?: string;
containerClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
desktopContainerClassName?: string;
mobileContainerClassName?: string;
desktopContentClassName?: string;
desktopWrapperClassName?: string;
mobileWrapperClassName?: string;
phoneFrameClassName?: string;
mobilePhoneFrameClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
ariaLabel?: string;
} }
const TimelinePhoneView = ({ const TimelinePhoneView: React.FC<TimelinePhoneViewProps> = ({ items, className = '' }) => {
items, const itemRefs = React.useRef<(HTMLElement | null)[]>([]);
showTextBox = true,
showDivider = false,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
animationType,
textboxLayout,
useInvertedBackground,
className = "",
containerClassName = "",
textBoxClassName = "",
titleClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
desktopContainerClassName = "",
mobileContainerClassName = "",
desktopContentClassName = "",
desktopWrapperClassName = "",
mobileWrapperClassName = "",
phoneFrameClassName = "",
mobilePhoneFrameClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
ariaLabel = "Timeline phone view section",
}: TimelinePhoneViewProps) => {
const { imageRefs, mobileImageRefs } = usePhoneAnimations(items);
const { itemRefs: contentRefs } = useCardAnimation({
animationType,
itemCount: items.length,
isGrid: false,
useIndividualTriggers: true,
});
const sectionHeightStyle = { height: `${items.length * 100}vh` };
return ( return (
<section <div className={`timeline-phone-view ${className}`}>
className={cls( {items.map((item, index) => (
"relative py-20 overflow-hidden md:overflow-visible w-full", <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="timeline-phone-item">
useInvertedBackground && "bg-foreground", {item.title}
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-full mx-auto flex flex-col gap-6", containerClassName)}>
{showTextBox && (
<div className="relative w-content-width mx-auto" >
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
/>
</div>
)}
{showDivider && (
<div className="relative w-content-width mx-auto h-px bg-accent md:hidden" />
)}
<div className="hidden md:flex relative" style={sectionHeightStyle}>
<div
className={cls(
"absolute top-0 left-0 flex flex-col w-[calc(var(--width-content-width)-var(--width-20)*2)] 2xl:w-[calc(var(--width-content-width)-var(--width-25)*2)] mx-auto right-0 z-10",
desktopContainerClassName
)}
style={sectionHeightStyle}
>
{items.map((item, index) => (
<div
key={`content-${index}`}
className={cls(
item.trigger,
"w-full mx-auto h-screen flex justify-center items-center",
desktopContentClassName
)}
>
<div
ref={(el) => { contentRefs.current[index] = el; }}
className={desktopWrapperClassName}
>
{item.content}
</div>
</div>
))}
</div>
<div className="sticky top-0 left-0 h-screen w-full overflow-hidden">
{items.map((item, itemIndex) => (
<div
key={`phones-${itemIndex}`}
className="h-screen w-full absolute top-0 left-0"
>
<div className="w-content-width mx-auto h-full flex flex-row justify-between items-center">
<PhoneFrame
key={`phone-${itemIndex}-1`}
imageSrc={item.imageOne}
videoSrc={item.videoOne}
imageAlt={item.imageAltOne}
videoAriaLabel={item.videoAriaLabelOne}
phoneRef={(el) => {
if (imageRefs.current) {
imageRefs.current[itemIndex * 2] = el;
}
}}
className={cls("w-20 2xl:w-25 h-[70vh]", phoneFrameClassName)}
/>
<PhoneFrame
key={`phone-${itemIndex}-2`}
imageSrc={item.imageTwo}
videoSrc={item.videoTwo}
imageAlt={item.imageAltTwo}
videoAriaLabel={item.videoAriaLabelTwo}
phoneRef={(el) => {
if (imageRefs.current) {
imageRefs.current[itemIndex * 2 + 1] = el;
}
}}
className={cls("w-20 2xl:w-25 h-[70vh]", phoneFrameClassName)}
/>
</div>
</div>
))}
</div>
</div> </div>
<div className={cls("md:hidden flex flex-col gap-20", mobileContainerClassName)}> ))}
{items.map((item, itemIndex) => ( </div>
<div
key={`mobile-item-${itemIndex}`}
className="flex flex-col gap-10"
>
<div className={mobileWrapperClassName}>
{item.content}
</div>
<div className="flex flex-row gap-6 justify-center">
<PhoneFrame
key={`mobile-phone-${itemIndex}-1`}
imageSrc={item.imageOne}
videoSrc={item.videoOne}
imageAlt={item.imageAltOne}
videoAriaLabel={item.videoAriaLabelOne}
phoneRef={(el) => {
if (mobileImageRefs.current) {
mobileImageRefs.current[itemIndex * 2] = el;
}
}}
className={cls("w-40 h-80", mobilePhoneFrameClassName)}
/>
<PhoneFrame
key={`mobile-phone-${itemIndex}-2`}
imageSrc={item.imageTwo}
videoSrc={item.videoTwo}
imageAlt={item.imageAltTwo}
videoAriaLabel={item.videoAriaLabelTwo}
phoneRef={(el) => {
if (mobileImageRefs.current) {
mobileImageRefs.current[itemIndex * 2 + 1] = el;
}
}}
className={cls("w-40 h-80", mobilePhoneFrameClassName)}
/>
</div>
</div>
))}
</div>
</div>
</section>
); );
}; };
TimelinePhoneView.displayName = "TimelinePhoneView"; export default TimelinePhoneView;
export default memo(TimelinePhoneView);

View File

@@ -1,202 +1,30 @@
"use client"; 'use client';
import React, { useEffect, useRef, memo, useState } from "react"; import React from 'react';
import { gsap } from "gsap"; import {
import { ScrollTrigger } from "gsap/ScrollTrigger"; ButtonConfig,
import CardStackTextBox from "../../CardStackTextBox"; ButtonAnimationType,
import { useCardAnimation } from "../../hooks/useCardAnimation"; CardAnimationType,
import { cls } from "@/lib/utils"; TitleSegment,
import type { LucideIcon } from "lucide-react"; } from '@/components/cardStack/types';
import type { ButtonConfig, ButtonAnimationType, CardAnimationType, TitleSegment } from "../../types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
gsap.registerPlugin(ScrollTrigger);
interface TimelineProcessFlowItem {
id: string;
content: React.ReactNode;
media: React.ReactNode;
reverse: boolean;
}
interface TimelineProcessFlowProps { interface TimelineProcessFlowProps {
items: TimelineProcessFlowItem[]; items: any[];
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
animationType: CardAnimationType;
useInvertedBackground?: InvertedBackground;
ariaLabel?: string;
className?: string; className?: string;
containerClassName?: string;
textBoxClassName?: string;
textBoxTitleClassName?: string;
textBoxDescriptionClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
itemClassName?: string;
mediaWrapperClassName?: string;
numberClassName?: string;
contentWrapperClassName?: string;
gapClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
} }
const TimelineProcessFlow = ({ const TimelineProcessFlow: React.FC<TimelineProcessFlowProps> = ({ items, className = '' }) => {
items, const itemRefs = React.useRef<(HTMLElement | null)[]>([]);
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
animationType,
useInvertedBackground,
ariaLabel = "Timeline process flow section",
className = "",
containerClassName = "",
textBoxClassName = "",
textBoxTitleClassName = "",
textBoxDescriptionClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
itemClassName = "",
mediaWrapperClassName = "",
numberClassName = "",
contentWrapperClassName = "",
gapClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
}: TimelineProcessFlowProps) => {
const processLineRef = useRef<HTMLDivElement>(null);
const { itemRefs } = useCardAnimation({ animationType, itemCount: items.length, useIndividualTriggers: true });
const [isMdScreen, setIsMdScreen] = useState(false);
useEffect(() => {
const checkScreenSize = () => {
setIsMdScreen(window.innerWidth >= 768);
};
checkScreenSize();
window.addEventListener('resize', checkScreenSize);
return () => window.removeEventListener('resize', checkScreenSize);
}, []);
useEffect(() => {
if (!processLineRef.current) return;
gsap.fromTo(
processLineRef.current,
{ yPercent: -100 },
{
yPercent: 0,
ease: "none",
scrollTrigger: {
trigger: ".timeline-line",
start: "top center",
end: "bottom center",
scrub: true,
},
}
);
return () => {
ScrollTrigger.getAll().forEach((trigger) => trigger.kill());
};
}, []);
return ( return (
<section <div className={`timeline-process-flow ${className}`}>
className={cls( {items.map((item, index) => (
"relative py-20 w-full", <div key={item.id || index} ref={(el) => { if (el) itemRefs.current[index] = el; }} className="timeline-process-item">
useInvertedBackground && "bg-foreground", {item.title}
className
)}
aria-label={ariaLabel}
>
<div className={cls("w-full flex flex-col gap-6", containerClassName)}>
<div className="relative w-content-width mx-auto">
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
/>
</div> </div>
<div className="relative w-full"> ))}
<div className="pointer-events-none absolute top-0 right-[var(--width-10)] md:right-auto md:left-1/2 md:-translate-x-1/2 w-px h-full z-10 overflow-hidden md:py-6" > </div>
<div className="relative timeline-line h-full bg-foreground overflow-hidden">
<div className="w-full h-full bg-accent" ref={processLineRef} />
</div>
</div>
<ol className={cls("relative w-content-width mx-auto flex flex-col gap-10 md:gap-20 md:p-6", isMdScreen && "card", "md:rounded-theme-capped", gapClassName)}>
{items.map((item, index) => (
<li
key={item.id}
ref={(el) => {
itemRefs.current[index] = el;
}}
className={cls(
"relative z-10 w-full flex flex-col gap-6 md:gap-0 md:flex-row justify-between",
item.reverse && "flex-col md:flex-row-reverse",
itemClassName
)}
>
<div
className={cls("relative w-70 md:w-[calc(50%-var(--width-5))]", mediaWrapperClassName)}
>
{item.media}
</div>
<div
className={cls(
"absolute! top-1/2 right-[calc(var(--height-8)/-2)] md:right-auto md:left-1/2 md:-translate-x-1/2 -translate-y-1/2 h-8 aspect-square rounded-theme flex items-center justify-center z-10 primary-button",
numberClassName
)}
>
<p className="text-sm text-primary-cta-text">{item.id}</p>
</div>
<div className={cls("relative w-70 md:w-[calc(50%-var(--width-5))]", contentWrapperClassName)}>
{item.content}
</div>
</li>
))}
</ol>
</div>
</div>
</section>
); );
}; };
TimelineProcessFlow.displayName = "TimelineProcessFlow"; export default TimelineProcessFlow;
export default memo(TimelineProcessFlow);

View File

@@ -1,149 +1,69 @@
import type { LucideIcon } from "lucide-react"; export interface CardStackItemShape {
import type { ButtonConfig, ButtonAnimationType } from "@/types/button"; id?: string;
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants"; title: string;
export type { ButtonConfig, ButtonAnimationType, TextboxLayout, InvertedBackground };
export type TitleSegment =
| { type: "text"; content: string }
| { type: "image"; src: string; alt?: string };
export interface TimelineCardStackItem {
id: number;
title: string;
description: string;
image: string;
imageAlt?: string;
} }
export type GridVariant = export interface ButtonConfig {
| "uniform-all-items-equal" text: string;
| "bento-grid" onClick?: () => void;
| "bento-grid-inverted" href?: string;
| "two-columns-alternating-heights" }
| "asymmetric-60-wide-40-narrow"
| "three-columns-all-equal-width"
| "four-items-2x2-equal-grid"
| "one-large-right-three-stacked-left"
| "items-top-row-full-width-bottom"
| "full-width-top-items-bottom-row"
| "one-large-left-three-stacked-right"
| "two-items-per-row"
| "timeline";
export type CardAnimationType = export type ButtonAnimationType = 'none' | 'opacity' | 'slide-up' | 'blur-reveal';
| "none" export type CardAnimationType = 'none' | 'opacity' | 'slide-up' | 'scale-rotate' | 'blur-reveal';
| "opacity" export type CardAnimationTypeWith3D = 'none' | 'opacity' | 'slide-up' | 'scale-rotate' | 'blur-reveal' | 'depth-3d';
| "slide-up" export type TextboxLayout = 'default' | 'split' | 'split-actions' | 'split-description' | 'inline-image';
| "scale-rotate" export type InvertedBackground = boolean;
| "blur-reveal"; export type GridVariant = 'uniform-all-items-equal' | 'bento-grid' | 'bento-grid-inverted' | 'two-columns-alternating-heights' | 'asymmetric-60-wide-40-narrow' | 'three-columns-all-equal-width' | 'four-items-2x2-equal-grid' | 'one-large-right-three-stacked-left' | 'items-top-row-full-width-bottom' | 'full-width-top-items-bottom-row' | 'one-large-left-three-stacked-right' | 'two-items-per-row' | 'timeline';
export type CardAnimationTypeWith3D = CardAnimationType | "depth-3d"; export interface TitleSegment {
type: 'text' | 'image';
content?: string;
src?: string;
alt?: string;
}
export interface CardStackProps {
children: React.ReactNode;
className?: string;
}
export interface TextBoxProps { export interface TextBoxProps {
title?: string; title: string;
titleSegments?: TitleSegment[]; description: string;
description?: string; className?: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground?: InvertedBackground;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
} }
export interface CardStackProps extends TextBoxProps { export interface UseCardAnimationReturn {
children: React.ReactNode; isActive: boolean;
mode?: "auto" | "buttons"; isMobile: boolean;
gridVariant?: GridVariant; itemRefs: React.RefObject<HTMLElement>[];
uniformGridCustomHeightClasses?: string; containerRef?: React.RefObject<HTMLElement>;
gridRowsClassName?: string; perspectiveRef?: React.RefObject<HTMLElement>;
itemHeightClassesOverride?: string[]; bottomContentRef?: React.RefObject<HTMLElement>;
animationType: CardAnimationType | CardAnimationTypeWith3D;
supports3DAnimation?: boolean;
carouselThreshold?: number;
bottomContent?: React.ReactNode;
className?: string;
containerClassName?: string;
gridClassName?: string;
carouselClassName?: string;
carouselItemClassName?: string;
controlsClassName?: string;
ariaLabel?: string;
} }
export interface GridLayoutProps extends TextBoxProps { export interface ArrowCarouselProps {
children: React.ReactNode; items: CardStackItemShape[];
itemCount: number; className?: string;
gridVariant?: GridVariant;
uniformGridCustomHeightClasses?: string;
gridRowsClassName?: string;
itemHeightClassesOverride?: string[];
animationType: CardAnimationType | CardAnimationTypeWith3D;
supports3DAnimation?: boolean;
bottomContent?: React.ReactNode;
className?: string;
containerClassName?: string;
gridClassName?: string;
ariaLabel: string;
} }
export interface AutoCarouselProps extends TextBoxProps { export interface AutoCarouselProps {
children: React.ReactNode; items: CardStackItemShape[];
uniformGridCustomHeightClasses?: string; className?: string;
animationType: CardAnimationType;
speed?: number;
bottomContent?: React.ReactNode;
className?: string;
containerClassName?: string;
carouselClassName?: string;
itemClassName?: string;
ariaLabel: string;
showTextBox?: boolean;
dualMarquee?: boolean;
topMarqueeDirection?: "left" | "right";
bottomMarqueeDirection?: "left" | "right";
bottomCarouselClassName?: string;
marqueeGapClassName?: string;
} }
export interface ButtonCarouselProps extends TextBoxProps { export interface ButtonCarouselProps {
children: React.ReactNode; items: CardStackItemShape[];
uniformGridCustomHeightClasses?: string; className?: string;
animationType: CardAnimationType;
bottomContent?: React.ReactNode;
className?: string;
containerClassName?: string;
carouselClassName?: string;
carouselItemClassName?: string;
controlsClassName?: string;
ariaLabel: string;
} }
export interface FullWidthCarouselProps extends TextBoxProps { export interface FullWidthCarouselProps {
children: React.ReactNode; items: CardStackItemShape[];
className?: string; className?: string;
containerClassName?: string;
carouselClassName?: string;
dotsClassName?: string;
ariaLabel: string;
} }
export interface ArrowCarouselProps extends TextBoxProps { export interface GridLayoutProps {
children: React.ReactNode; items: CardStackItemShape[];
className?: string; className?: string;
containerClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
ariaLabel: string;
} }

View File

@@ -1,156 +1,31 @@
"use client"; 'use client';
import { memo, useMemo, useCallback } from "react"; import React from 'react';
import { useRouter } from "next/navigation"; import { Product } from '@/lib/api/product';
import Input from "@/components/form/Input";
import ProductDetailVariantSelect from "@/components/ecommerce/productDetail/ProductDetailVariantSelect";
import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
import { cls } from "@/lib/utils";
import { useProducts } from "@/hooks/useProducts";
import ProductCatalogItem from "./ProductCatalogItem";
import type { CatalogProduct } from "./ProductCatalogItem";
interface ProductCatalogProps { interface ProductCatalogProps {
layout: "page" | "section"; products?: Product[];
products?: CatalogProduct[]; loading?: boolean;
searchValue?: string; className?: string;
onSearchChange?: (value: string) => void;
searchPlaceholder?: string;
filters?: ProductVariant[];
emptyMessage?: string;
className?: string;
gridClassName?: string;
cardClassName?: string;
imageClassName?: string;
searchClassName?: string;
filterClassName?: string;
toolbarClassName?: string;
} }
const ProductCatalog = ({ const ProductCatalog: React.FC<ProductCatalogProps> = ({ products = [], loading = false, className = '' }) => {
layout, return (
products: productsProp, <div className={`product-catalog ${className}`}>
searchValue = "", {loading ? (
onSearchChange, <div>Loading...</div>
searchPlaceholder = "Search products...", ) : (
filters, <div className="product-list">
emptyMessage = "No products found", {products.map((product) => (
className = "", <div key={product.id} className="product-item">
gridClassName = "", <h3>{product.name}</h3>
cardClassName = "", <p>{product.price}</p>
imageClassName = "", </div>
searchClassName = "", ))}
filterClassName = "", </div>
toolbarClassName = "", )}
}: ProductCatalogProps) => { </div>
const router = useRouter(); );
const { products: fetchedProducts, isLoading } = useProducts();
const handleProductClick = useCallback((productId: string) => {
router.push(`/shop/${productId}`);
}, [router]);
const products: CatalogProduct[] = useMemo(() => {
if (productsProp && productsProp.length > 0) {
return productsProp;
}
if (fetchedProducts.length === 0) {
return [];
}
return fetchedProducts.map((product) => ({
id: product.id,
name: product.name,
price: product.price,
imageSrc: product.imageSrc,
imageAlt: product.imageAlt || product.name,
rating: product.rating || 0,
reviewCount: product.reviewCount,
category: product.brand,
onProductClick: () => handleProductClick(product.id),
}));
}, [productsProp, fetchedProducts, handleProductClick]);
if (isLoading && (!productsProp || productsProp.length === 0)) {
return (
<section
className={cls(
"relative w-content-width mx-auto",
layout === "page" ? "pt-hero-page-padding pb-20" : "py-20",
className
)}
>
<p className="text-sm text-foreground/50 text-center py-20">
Loading products...
</p>
</section>
);
}
return (
<section
className={cls(
"relative w-content-width mx-auto",
layout === "page" ? "pt-hero-page-padding pb-20" : "py-20",
className
)}
>
{(onSearchChange || (filters && filters.length > 0)) && (
<div
className={cls(
"flex flex-col md:flex-row gap-4 md:items-end mb-6",
toolbarClassName
)}
>
{onSearchChange && (
<Input
value={searchValue}
onChange={onSearchChange}
placeholder={searchPlaceholder}
ariaLabel={searchPlaceholder}
className={cls("flex-1 w-full h-9 text-sm", searchClassName)}
/>
)}
{filters && filters.length > 0 && (
<div className="flex gap-4 items-end">
{filters.map((filter) => (
<ProductDetailVariantSelect
key={filter.label}
variant={filter}
selectClassName={filterClassName}
/>
))}
</div>
)}
</div>
)}
{products.length === 0 ? (
<p className="text-sm text-foreground/50 text-center py-20">
{emptyMessage}
</p>
) : (
<div
className={cls(
"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6",
gridClassName
)}
>
{products.map((product) => (
<ProductCatalogItem
key={product.id}
product={product}
className={cardClassName}
imageClassName={imageClassName}
/>
))}
</div>
)}
</section>
);
}; };
ProductCatalog.displayName = "ProductCatalog"; export default ProductCatalog;
export default memo(ProductCatalog);

View File

@@ -1,182 +1,21 @@
"use client"; 'use client';
import { Fragment } from "react"; import React from 'react';
import CardStackTextBox from "@/components/cardStack/CardStackTextBox"; import { TitleSegment, ButtonAnimationType } from '@/components/cardStack/types';
import MediaContent from "@/components/shared/MediaContent";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useButtonAnimation } from "@/components/hooks/useButtonAnimation";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig } from "@/types/button";
import type { TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
interface BulletPoint {
title: string;
description: string;
icon?: LucideIcon;
}
interface SplitAboutProps { interface SplitAboutProps {
title: string; title: string;
titleSegments?: TitleSegment[];
description: string; description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
bulletPoints: BulletPoint[];
imageSrc?: string;
videoSrc?: string;
imageAlt?: string;
videoAriaLabel?: string;
ariaLabel?: string;
imagePosition?: "left" | "right";
mediaAnimation: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
className?: string; className?: string;
containerClassName?: string;
textBoxClassName?: string;
titleClassName?: string;
titleImageWrapperClassName?: string;
titleImageClassName?: string;
descriptionClassName?: string;
tagClassName?: string;
buttonContainerClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
contentClassName?: string;
bulletPointClassName?: string;
bulletTitleClassName?: string;
bulletDescriptionClassName?: string;
mediaWrapperClassName?: string;
imageClassName?: string;
} }
const SplitAbout = ({ const SplitAbout: React.FC<SplitAboutProps> = ({ title, description, className = '' }) => {
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
bulletPoints,
imageSrc,
videoSrc,
imageAlt = "",
videoAriaLabel = "About section video",
ariaLabel = "About section",
imagePosition = "right",
mediaAnimation,
textboxLayout,
useInvertedBackground,
className = "",
containerClassName = "",
textBoxClassName = "",
titleClassName = "",
titleImageWrapperClassName = "",
titleImageClassName = "",
descriptionClassName = "",
tagClassName = "",
buttonContainerClassName = "",
buttonClassName = "",
buttonTextClassName = "",
contentClassName = "",
bulletPointClassName = "",
bulletTitleClassName = "",
bulletDescriptionClassName = "",
mediaWrapperClassName = "",
imageClassName = "",
}: SplitAboutProps) => {
const theme = useTheme();
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const { containerRef: mediaContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
const { containerRef: bulletPointsContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
const mediaContent = (
<div className={cls("w-full md:w-6/10 2xl:w-7/10 overflow-hidden rounded-theme-capped card md:relative p-4", mediaWrapperClassName)}>
<div ref={mediaContainerRef} className="md:relative w-full md:h-full">
<MediaContent
imageSrc={imageSrc}
videoSrc={videoSrc}
imageAlt={imageAlt}
videoAriaLabel={videoAriaLabel}
imageClassName={cls("z-1 w-full h-auto object-cover rounded-theme-capped md:absolute md:inset-0 md:h-full", imageClassName)}
/>
</div>
</div>
);
return ( return (
<section <div className={`split-about ${className}`}>
aria-label={ariaLabel} <h2>{title}</h2>
className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)} <p>{description}</p>
> </div>
<div className={cls("w-content-width mx-auto flex flex-col gap-8", containerClassName)}>
<CardStackTextBox
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
textBoxClassName={textBoxClassName}
titleClassName={titleClassName}
titleImageWrapperClassName={titleImageWrapperClassName}
titleImageClassName={titleImageClassName}
descriptionClassName={descriptionClassName}
tagClassName={tagClassName}
buttonContainerClassName={buttonContainerClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
/>
<div className={cls("flex flex-col md:flex-row gap-6 md:items-stretch")}>
{imagePosition === "left" && mediaContent}
<div ref={bulletPointsContainerRef} className={cls("w-full md:w-4/10 2xl:w-3/10 rounded-theme-capped card p-6 flex flex-col gap-6 justify-center", contentClassName)}>
{bulletPoints.map((point, index) => {
const Icon = point.icon;
return (
<Fragment key={index}>
<div className={cls("relative z-1 flex flex-col gap-2", bulletPointClassName)}>
{Icon && (
<div className="h-10 w-fit aspect-square rounded-theme primary-button flex items-center justify-center flex-shrink-0 mb-1">
<Icon className="h-[40%] w-[40%] text-primary-cta-text" strokeWidth={1.5} />
</div>
)}
<div className="flex flex-col gap-0">
<h3 className={cls("text-xl font-medium", shouldUseLightText && "text-background", bulletTitleClassName)}>
{point.title}
</h3>
<p className={cls("text-base leading-[1.4]", shouldUseLightText ? "text-background" : "text-foreground", bulletDescriptionClassName)}>
{point.description}
</p>
</div>
</div>
{index < bulletPoints.length - 1 && (
<div className="relative z-1 w-full border-b border-accent/40" />
)}
</Fragment>
);
})}
</div>
{imagePosition === "right" && mediaContent}
</div>
</div>
</section>
); );
}; };
SplitAbout.displayName = "SplitAbout";
export default SplitAbout; export default SplitAbout;

View File

@@ -1,131 +1,91 @@
"use client"; 'use client';
import ContactForm from "@/components/form/ContactForm"; import React, { useState } from 'react';
import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds"; import TextAnimation from '@/components/text/TextAnimation';
import { cls } from "@/lib/utils";
import { LucideIcon } from "lucide-react";
import { sendContactEmail } from "@/utils/sendContactEmail";
import type { ButtonAnimationType } from "@/types/button";
type ContactCenterBackgroundProps = Extract<
HeroBackgroundVariantProps,
| { variant: "plain" }
| { variant: "animated-grid" }
| { variant: "canvas-reveal" }
| { variant: "cell-wave" }
| { variant: "downward-rays-animated" }
| { variant: "downward-rays-animated-grid" }
| { variant: "downward-rays-static" }
| { variant: "downward-rays-static-grid" }
| { variant: "gradient-bars" }
| { variant: "radial-gradient" }
| { variant: "rotated-rays-animated" }
| { variant: "rotated-rays-animated-grid" }
| { variant: "rotated-rays-static" }
| { variant: "rotated-rays-static-grid" }
| { variant: "sparkles-gradient" }
>;
interface ContactCenterProps { interface ContactCenterProps {
title: string; tag: string;
description: string; title: string;
tag: string; description: string;
tagIcon?: LucideIcon; background: { variant: string };
tagAnimation?: ButtonAnimationType; useInvertedBackground: boolean;
background: ContactCenterBackgroundProps; inputPlaceholder?: string;
useInvertedBackground: boolean; buttonText?: string;
tagClassName?: string; termsText?: string;
inputPlaceholder?: string; onSubmit?: (email: string) => void;
buttonText?: string; className?: string;
termsText?: string; containerClassName?: string;
onSubmit?: (email: string) => void; contentClassName?: string;
ariaLabel?: string; tagClassName?: string;
className?: string; titleClassName?: string;
containerClassName?: string; descriptionClassName?: string;
contentClassName?: string; formWrapperClassName?: string;
titleClassName?: string; formClassName?: string;
descriptionClassName?: string; inputClassName?: string;
formWrapperClassName?: string; buttonClassName?: string;
formClassName?: string; buttonTextClassName?: string;
inputClassName?: string; termsClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
termsClassName?: string;
} }
const ContactCenter = ({ const ContactCenter: React.FC<ContactCenterProps> = ({
title, tag,
description, title,
tag, description,
tagIcon, background,
tagAnimation, useInvertedBackground,
background, inputPlaceholder = 'Enter your email',
useInvertedBackground, buttonText = 'Sign Up',
tagClassName = "", termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.", onSubmit,
inputPlaceholder = "Enter your email", className = '',
buttonText = "Sign Up", containerClassName = '',
termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.", contentClassName = '',
onSubmit, tagClassName = '',
ariaLabel = "Contact section", titleClassName = '',
className = "", descriptionClassName = '',
containerClassName = "", formWrapperClassName = '',
contentClassName = "", formClassName = '',
titleClassName = "", inputClassName = '',
descriptionClassName = "", buttonClassName = '',
formWrapperClassName = "", buttonTextClassName = '',
formClassName = "", termsClassName = '',
inputClassName = "", }) => {
buttonClassName = "", const [email, setEmail] = useState('');
buttonTextClassName = "",
termsClassName = "",
}: ContactCenterProps) => {
const handleSubmit = async (email: string) => { const handleSubmit = () => {
try { if (onSubmit && email) {
await sendContactEmail({ email }); onSubmit(email);
console.log("Email send successfully"); }
} catch (error) { };
console.error("Failed to send email:", error);
}
};
return ( return (
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}> <section className={`contact-center ${className}`}>
<div className={cls("w-content-width mx-auto relative z-10", containerClassName)}> <div className={`container ${containerClassName}`}>
<div className={cls("relative w-full card p-6 md:p-0 py-20 md:py-20 rounded-theme-capped flex items-center justify-center", contentClassName)}> <div className={`content ${contentClassName}`}>
<div className="relative z-10 w-full md:w-1/2"> {tag && <div className={`tag ${tagClassName}`}>{tag}</div>}
<ContactForm <TextAnimation text={title} className={titleClassName} />
tag={tag} <p className={descriptionClassName}>{description}</p>
tagIcon={tagIcon} <div className={`form-wrapper ${formWrapperClassName}`}>
tagAnimation={tagAnimation} <div className={formClassName}>
title={title} <input
description={description} type="email"
useInvertedBackground={useInvertedBackground} value={email}
inputPlaceholder={inputPlaceholder} onChange={(e) => setEmail(e.target.value)}
buttonText={buttonText} placeholder={inputPlaceholder}
termsText={termsText} className={inputClassName}
onSubmit={handleSubmit} />
centered={true} <button
tagClassName={tagClassName} onClick={handleSubmit}
titleClassName={titleClassName} className={buttonClassName}
descriptionClassName={descriptionClassName} >
formWrapperClassName={cls("md:w-8/10 2xl:w-6/10", formWrapperClassName)} <span className={buttonTextClassName}>{buttonText}</span>
formClassName={formClassName} </button>
inputClassName={inputClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
termsClassName={termsClassName}
/>
</div>
<div className="absolute inset w-full h-full z-0 rounded-theme-capped overflow-hidden" >
<HeroBackgrounds {...background} />
</div>
</div>
</div> </div>
</section> </div>
); {termsText && <p className={`terms ${termsClassName}`}>{termsText}</p>}
</div>
</div>
</section>
);
}; };
ContactCenter.displayName = "ContactCenter";
export default ContactCenter; export default ContactCenter;

View File

@@ -1,171 +1,52 @@
"use client"; 'use client';
import ContactForm from "@/components/form/ContactForm"; import React, { useState } from 'react';
import MediaContent from "@/components/shared/MediaContent";
import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds";
import { cls } from "@/lib/utils";
import { useButtonAnimation } from "@/components/hooks/useButtonAnimation";
import { LucideIcon } from "lucide-react";
import { sendContactEmail } from "@/utils/sendContactEmail";
import type { ButtonAnimationType } from "@/types/button";
type ContactSplitBackgroundProps = Extract<
HeroBackgroundVariantProps,
| { variant: "plain" }
| { variant: "animated-grid" }
| { variant: "canvas-reveal" }
| { variant: "cell-wave" }
| { variant: "downward-rays-animated" }
| { variant: "downward-rays-animated-grid" }
| { variant: "downward-rays-static" }
| { variant: "downward-rays-static-grid" }
| { variant: "gradient-bars" }
| { variant: "radial-gradient" }
| { variant: "rotated-rays-animated" }
| { variant: "rotated-rays-animated-grid" }
| { variant: "rotated-rays-static" }
| { variant: "rotated-rays-static-grid" }
| { variant: "sparkles-gradient" }
>;
interface ContactSplitProps { interface ContactSplitProps {
title: string; title: string;
description: string; description: string;
tag: string; contactInfo: string;
tagIcon?: LucideIcon; onSubmit?: (email: string) => void;
tagAnimation?: ButtonAnimationType; className?: string;
background: ContactSplitBackgroundProps;
useInvertedBackground: boolean;
imageSrc?: string;
videoSrc?: string;
imageAlt?: string;
videoAriaLabel?: string;
mediaPosition?: "left" | "right";
mediaAnimation: ButtonAnimationType;
inputPlaceholder?: string;
buttonText?: string;
termsText?: string;
onSubmit?: (email: string) => void;
ariaLabel?: string;
className?: string;
containerClassName?: string;
contentClassName?: string;
contactFormClassName?: string;
tagClassName?: string;
titleClassName?: string;
descriptionClassName?: string;
formWrapperClassName?: string;
formClassName?: string;
inputClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
termsClassName?: string;
mediaWrapperClassName?: string;
mediaClassName?: string;
} }
const ContactSplit = ({ const ContactSplit: React.FC<ContactSplitProps> = ({
title, title,
description, description,
tag, contactInfo,
tagIcon, onSubmit,
tagAnimation, className = '',
background, }) => {
useInvertedBackground, const [email, setEmail] = useState('');
imageSrc,
videoSrc,
imageAlt = "",
videoAriaLabel = "Contact section video",
mediaPosition = "right",
mediaAnimation,
inputPlaceholder = "Enter your email",
buttonText = "Sign Up",
termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.",
onSubmit,
ariaLabel = "Contact section",
className = "",
containerClassName = "",
contentClassName = "",
contactFormClassName = "",
tagClassName = "",
titleClassName = "",
descriptionClassName = "",
formWrapperClassName = "",
formClassName = "",
inputClassName = "",
buttonClassName = "",
buttonTextClassName = "",
termsClassName = "",
mediaWrapperClassName = "",
mediaClassName = "",
}: ContactSplitProps) => {
const { containerRef: mediaContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
const handleSubmit = async (email: string) => { const handleEmailSubmit = () => {
try { if (onSubmit && email) {
await sendContactEmail({ email }); onSubmit(email);
console.log("Email send successfully"); }
} catch (error) { };
console.error("Failed to send email:", error);
}
};
const contactContent = ( return (
<div className="relative card rounded-theme-capped p-6 py-15 md:py-6 flex items-center justify-center"> <section className={`contact-split ${className}`}>
<ContactForm <div className="contact-split-container">
tag={tag} <div className="contact-split-left">
tagIcon={tagIcon} <h2>{title}</h2>
tagAnimation={tagAnimation} <p>{description}</p>
title={title}
description={description}
useInvertedBackground={useInvertedBackground}
inputPlaceholder={inputPlaceholder}
buttonText={buttonText}
termsText={termsText}
onSubmit={handleSubmit}
centered={true}
className={cls("w-full", contactFormClassName)}
tagClassName={tagClassName}
titleClassName={titleClassName}
descriptionClassName={descriptionClassName}
formWrapperClassName={cls("w-full md:w-8/10 2xl:w-7/10", formWrapperClassName)}
formClassName={formClassName}
inputClassName={inputClassName}
buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
termsClassName={termsClassName}
/>
<div className="absolute inset w-full h-full z-0 rounded-theme-capped overflow-hidden" >
<HeroBackgrounds {...background} />
</div>
</div> </div>
); <div className="contact-split-right">
<div className="form-group">
const mediaContent = ( <input
<div ref={mediaContainerRef} className={cls("overflow-hidden rounded-theme-capped card h-130", mediaWrapperClassName)}> type="email"
<MediaContent value={email}
imageSrc={imageSrc} onChange={(e) => setEmail(e.target.value)}
videoSrc={videoSrc} placeholder="Enter your email"
imageAlt={imageAlt}
videoAriaLabel={videoAriaLabel}
imageClassName={cls("relative z-1 w-full h-full object-cover", mediaClassName)}
/> />
<button onClick={handleEmailSubmit}>Get Started</button>
</div>
<p className="contact-info">{contactInfo}</p>
</div> </div>
); </div>
</section>
return ( );
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
<div className={cls("w-content-width mx-auto relative z-10", containerClassName)}>
<div className={cls("grid grid-cols-1 md:grid-cols-2 gap-6 md:auto-rows-fr", contentClassName)}>
{mediaPosition === "left" && mediaContent}
{contactContent}
{mediaPosition === "right" && mediaContent}
</div>
</div>
</section>
);
}; };
ContactSplit.displayName = "ContactSplit";
export default ContactSplit; export default ContactSplit;

View File

@@ -1,214 +1,43 @@
"use client"; 'use client';
import { useState } from "react"; import React, { useState } from 'react';
import TextAnimation from "@/components/text/TextAnimation";
import Button from "@/components/button/Button";
import Input from "@/components/form/Input";
import Textarea from "@/components/form/Textarea";
import MediaContent from "@/components/shared/MediaContent";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useButtonAnimation } from "@/components/hooks/useButtonAnimation";
import { getButtonProps } from "@/lib/buttonUtils";
import type { AnimationType } from "@/components/text/types";
import type { ButtonAnimationType } from "@/types/button";
import {sendContactEmail} from "@/utils/sendContactEmail";
export interface InputField {
name: string;
type: string;
placeholder: string;
required?: boolean;
className?: string;
}
export interface TextareaField {
name: string;
placeholder: string;
rows?: number;
required?: boolean;
className?: string;
}
interface ContactSplitFormProps { interface ContactSplitFormProps {
title: string; title: string;
description: string; description: string;
inputs: InputField[]; className?: string;
textarea?: TextareaField;
useInvertedBackground: boolean;
imageSrc?: string;
videoSrc?: string;
imageAlt?: string;
videoAriaLabel?: string;
mediaPosition?: "left" | "right";
mediaAnimation: ButtonAnimationType;
buttonText?: string;
onSubmit?: (data: Record<string, string>) => void;
ariaLabel?: string;
className?: string;
containerClassName?: string;
contentClassName?: string;
formCardClassName?: string;
titleClassName?: string;
descriptionClassName?: string;
buttonClassName?: string;
buttonTextClassName?: string;
mediaWrapperClassName?: string;
mediaClassName?: string;
} }
const ContactSplitForm = ({ const ContactSplitForm: React.FC<ContactSplitFormProps> = ({
title, title,
description, description,
inputs, className = '',
textarea, }) => {
useInvertedBackground, const [email, setEmail] = useState('');
imageSrc,
videoSrc,
imageAlt = "",
videoAriaLabel = "Contact section video",
mediaPosition = "right",
mediaAnimation,
buttonText = "Submit",
onSubmit,
ariaLabel = "Contact section",
className = "",
containerClassName = "",
contentClassName = "",
formCardClassName = "",
titleClassName = "",
descriptionClassName = "",
buttonClassName = "",
buttonTextClassName = "",
mediaWrapperClassName = "",
mediaClassName = "",
}: ContactSplitFormProps) => {
const theme = useTheme();
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const { containerRef: mediaContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
// Validate minimum inputs requirement const handleSubmit = () => {
if (inputs.length < 2) { if (email) {
throw new Error("ContactSplitForm requires at least 2 inputs"); console.log('Form submitted with email:', email);
} }
};
// Initialize form data dynamically return (
const initialFormData: Record<string, string> = {}; <section className={`contact-split-form ${className}`}>
inputs.forEach(input => { <div className="contact-form-container">
initialFormData[input.name] = ""; <h2>{title}</h2>
}); <p>{description}</p>
if (textarea) { <div className="form-group">
initialFormData[textarea.name] = ""; <input
} type="email"
value={email}
const [formData, setFormData] = useState(initialFormData); onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
const handleSubmit = async (e: React.FormEvent) => { />
e.preventDefault(); <button onClick={handleSubmit}>Submit</button>
try {
await sendContactEmail({ formData });
console.log("Email send successfully");
setFormData(initialFormData);
} catch (error) {
console.error("Failed to send email:", error);
}
};
const getButtonConfigProps = () => {
if (theme.defaultButtonVariant === "hover-bubble") {
return { bgClassName: "w-full" };
}
if (theme.defaultButtonVariant === "icon-arrow") {
return { className: "justify-between" };
}
return {};
};
const formContent = (
<div className={cls("card rounded-theme-capped p-6 md:p-10 flex items-center justify-center", formCardClassName)}>
<form onSubmit={handleSubmit} className="relative z-1 w-full flex flex-col gap-6">
<div className="w-full flex flex-col gap-0 text-center">
<TextAnimation
type={theme.defaultTextAnimation as AnimationType}
text={title}
variant="trigger"
className={cls("text-4xl font-medium leading-[1.175] text-balance", shouldUseLightText ? "text-background" : "text-foreground", titleClassName)}
/>
<TextAnimation
type={theme.defaultTextAnimation as AnimationType}
text={description}
variant="words-trigger"
className={cls("text-base leading-[1.15] text-balance", shouldUseLightText ? "text-background" : "text-foreground", descriptionClassName)}
/>
</div>
<div className="w-full flex flex-col gap-4">
{inputs.map((input) => (
<Input
key={input.name}
type={input.type}
placeholder={input.placeholder}
value={formData[input.name] || ""}
onChange={(value) => setFormData({ ...formData, [input.name]: value })}
required={input.required}
ariaLabel={input.placeholder}
className={input.className}
/>
))}
{textarea && (
<Textarea
placeholder={textarea.placeholder}
value={formData[textarea.name] || ""}
onChange={(value) => setFormData({ ...formData, [textarea.name]: value })}
required={textarea.required}
rows={textarea.rows || 5}
ariaLabel={textarea.placeholder}
className={textarea.className}
/>
)}
<Button
{...getButtonProps(
{ text: buttonText, props: getButtonConfigProps() },
0,
theme.defaultButtonVariant,
cls("w-full", buttonClassName),
cls("text-base", buttonTextClassName)
)}
type="submit"
/>
</div>
</form>
</div> </div>
); </div>
</section>
const mediaContent = ( );
<div ref={mediaContainerRef} className={cls("overflow-hidden rounded-theme-capped card md:relative md:h-full", mediaWrapperClassName)}>
<MediaContent
imageSrc={imageSrc}
videoSrc={videoSrc}
imageAlt={imageAlt}
videoAriaLabel={videoAriaLabel}
imageClassName={cls("w-full md:absolute md:inset-0 md:h-full object-cover", mediaClassName)}
/>
</div>
);
return (
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
<div className={cls("w-content-width mx-auto", containerClassName)}>
<div className={cls("grid grid-cols-1 md:grid-cols-2 gap-6 md:auto-rows-fr", contentClassName)}>
{mediaPosition === "left" && mediaContent}
{formContent}
{mediaPosition === "right" && mediaContent}
</div>
</div>
</section>
);
}; };
ContactSplitForm.displayName = "ContactSplitForm";
export default ContactSplitForm; export default ContactSplitForm;

View File

@@ -0,0 +1,53 @@
'use client';
import FeatureCardTwentyFive from './FeatureCardTwentyFive';
interface FeatureCardTwentyFiveWithSavingProps {
title: string;
description: string;
tag?: string;
tagIcon?: any;
features: Array<{
title: string;
description: string;
icon: any;
mediaItems: Array<{ imageSrc: string; imageAlt: string }>;
}>;
animationType: 'none' | 'opacity' | 'slide-up' | 'scale-rotate' | 'blur-reveal' | 'depth-3d';
textboxLayout: 'default' | 'split' | 'split-actions' | 'split-description' | 'inline-image';
useInvertedBackground: boolean;
onFeatureInteraction?: (featureData: any) => void;
workoutType?: 'cardio' | 'training';
}
export function FeatureCardTwentyFiveWithSaving({
title,
description,
tag,
tagIcon,
features,
animationType,
textboxLayout,
useInvertedBackground,
onFeatureInteraction,
workoutType,
}: FeatureCardTwentyFiveWithSavingProps) {
const handleFeatureInteraction = (featureIndex: number, data?: any) => {
onFeatureInteraction?.(data);
};
return (
<FeatureCardTwentyFive
title={title}
description={description}
tag={tag}
tagIcon={tagIcon}
features={features}
animationType={animationType}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
/>
);
}
export default FeatureCardTwentyFiveWithSaving;

View File

@@ -0,0 +1,70 @@
'use client';
import { useWorkoutStorage } from '@/hooks/useWorkoutStorage';
import MetricCardFourteen from './MetricCardFourteen';
import { useEffect, useState } from 'react';
interface MetricCardFourteenWithSavingProps {
title: string;
tag: string;
tagAnimation?: 'none' | 'opacity' | 'slide-up' | 'blur-reveal';
metrics: Array<{
id: string;
value: string;
description: string;
}>;
metricsAnimation: 'none' | 'opacity' | 'slide-up' | 'blur-reveal';
useInvertedBackground: boolean;
}
export function MetricCardFourteenWithSaving({
title,
tag,
tagAnimation,
metrics,
metricsAnimation,
useInvertedBackground,
}: MetricCardFourteenWithSavingProps) {
const { metrics: userMetrics, updateMetrics } = useWorkoutStorage();
const [displayMetrics, setDisplayMetrics] = useState(metrics);
useEffect(() => {
if (userMetrics) {
// Dynamically update metrics based on saved data
const updatedMetrics = metrics.map(metric => {
let value = metric.value;
if (metric.id === '1' && userMetrics.totalDistance > 0) {
// Update steps/distance metric
value = `${Math.round(userMetrics.totalDistance).toLocaleString()}+`;
} else if (metric.id === '2' && userMetrics.totalWeight > 0) {
// Update volume metric
value = `${Math.round(userMetrics.totalWeight)} kg`;
} else if (metric.id === '3' && userMetrics.totalDistance > 0) {
// Update distance metric
value = `${Math.round(userMetrics.totalDistance)}+ km`;
} else if (metric.id === '4' && userMetrics.consistency > 0) {
// Update consistency metric
value = `${userMetrics.consistency} days`;
}
return { ...metric, value };
});
setDisplayMetrics(updatedMetrics);
}
}, [userMetrics, metrics]);
return (
<MetricCardFourteen
title={title}
tag={tag}
tagAnimation={tagAnimation}
metrics={displayMetrics}
metricsAnimation={metricsAnimation}
useInvertedBackground={useInvertedBackground}
/>
);
}
export default MetricCardFourteenWithSaving;

View File

@@ -1,248 +1,37 @@
"use client"; 'use client';
import { memo } from "react"; import React from 'react';
import CardStack from "@/components/cardStack/CardStack";
import Button from "@/components/button/Button";
import PricingBadge from "@/components/shared/PricingBadge";
import PricingFeatureList from "@/components/shared/PricingFeatureList";
import { getButtonProps } from "@/lib/buttonUtils";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, CardAnimationType, TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type PricingPlan = { interface PricingCard {
id: string; id: string;
badge: string; name: string;
badgeIcon?: LucideIcon; price: string;
price: string; features: string[];
subtitle: string; }
buttons: ButtonConfig[];
features: string[];
};
interface PricingCardEightProps { interface PricingCardEightProps {
plans: PricingPlan[]; cards: PricingCard[];
carouselMode?: "auto" | "buttons"; className?: string;
uniformGridCustomHeightClasses?: string;
animationType: CardAnimationType;
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
ariaLabel?: string;
className?: string;
containerClassName?: string;
cardClassName?: string;
textBoxTitleClassName?: string;
textBoxTitleImageWrapperClassName?: string;
textBoxTitleImageClassName?: string;
textBoxDescriptionClassName?: string;
badgeClassName?: string;
priceClassName?: string;
subtitleClassName?: string;
planButtonContainerClassName?: string;
planButtonClassName?: string;
featuresClassName?: string;
featureItemClassName?: string;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
interface PricingCardItemProps { const PricingCardEight: React.FC<PricingCardEightProps> = ({ cards, className = '' }) => {
plan: PricingPlan; return (
shouldUseLightText: boolean; <div className={`pricing-card-eight ${className}`}>
cardClassName?: string; {cards.map((card) => (
badgeClassName?: string; <div key={card.id} className="pricing-card">
priceClassName?: string; <h3>{card.name}</h3>
subtitleClassName?: string; <div className="price-section">
planButtonContainerClassName?: string; <span>{card.price}</span>
planButtonClassName?: string; </div>
featuresClassName?: string; <ul className="features-list">
featureItemClassName?: string; {card.features.map((feature, index) => (
} <li key={index}>{feature}</li>
const PricingCardItem = memo(({
plan,
shouldUseLightText,
cardClassName = "",
badgeClassName = "",
priceClassName = "",
subtitleClassName = "",
planButtonContainerClassName = "",
planButtonClassName = "",
featuresClassName = "",
featureItemClassName = "",
}: PricingCardItemProps) => {
const theme = useTheme();
const getButtonConfigProps = () => {
if (theme.defaultButtonVariant === "hover-bubble") {
return { bgClassName: "w-full" };
}
if (theme.defaultButtonVariant === "icon-arrow") {
return { className: "justify-between" };
}
return {};
};
return (
<div className={cls("relative h-full card text-foreground rounded-theme-capped p-3 flex flex-col gap-3", cardClassName)}>
<div className="relative secondary-button p-3 flex flex-col gap-3 rounded-theme-capped" >
<PricingBadge
badge={plan.badge}
badgeIcon={plan.badgeIcon}
className={badgeClassName}
/>
<div className="relative z-1 flex flex-col gap-1">
<div className="text-5xl font-medium text-foreground">
{plan.price}
</div>
<p className="text-base text-foreground">
{plan.subtitle}
</p>
</div>
{plan.buttons && plan.buttons.length > 0 && (
<div className={cls("relative z-1 w-full flex flex-col gap-3", planButtonContainerClassName)}>
{plan.buttons.slice(0, 2).map((button, index) => (
<Button
key={`${button.text}-${index}`}
{...getButtonProps(
{ ...button, props: { ...button.props, ...getButtonConfigProps() } },
index,
theme.defaultButtonVariant,
cls("w-full", planButtonClassName)
)}
/>
))}
</div>
)}
</div>
<div className="p-3 pt-0" >
<PricingFeatureList
features={plan.features}
shouldUseLightText={shouldUseLightText}
className={cls("mt-1", featuresClassName)}
featureItemClassName={featureItemClassName}
/>
</div>
</div>
);
});
PricingCardItem.displayName = "PricingCardItem";
const PricingCardEight = ({
plans,
carouselMode = "buttons",
uniformGridCustomHeightClasses,
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
ariaLabel = "Pricing section",
className = "",
containerClassName = "",
cardClassName = "",
textBoxTitleClassName = "",
textBoxTitleImageWrapperClassName = "",
textBoxTitleImageClassName = "",
textBoxDescriptionClassName = "",
badgeClassName = "",
priceClassName = "",
subtitleClassName = "",
planButtonContainerClassName = "",
planButtonClassName = "",
featuresClassName = "",
featureItemClassName = "",
gridClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
}: PricingCardEightProps) => {
const theme = useTheme();
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
return (
<CardStack
useInvertedBackground={useInvertedBackground}
mode={carouselMode}
gridVariant="uniform-all-items-equal"
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
animationType={animationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
carouselClassName={carouselClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
titleImageClassName={textBoxTitleImageClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
ariaLabel={ariaLabel}
>
{plans.map((plan, index) => (
<PricingCardItem
key={`${plan.id}-${index}`}
plan={plan}
shouldUseLightText={shouldUseLightText}
cardClassName={cardClassName}
badgeClassName={badgeClassName}
priceClassName={priceClassName}
subtitleClassName={subtitleClassName}
planButtonContainerClassName={planButtonContainerClassName}
planButtonClassName={planButtonClassName}
featuresClassName={featuresClassName}
featureItemClassName={featureItemClassName}
/>
))} ))}
</CardStack> </ul>
); </div>
))}
</div>
);
}; };
PricingCardEight.displayName = "PricingCardEight";
export default PricingCardEight; export default PricingCardEight;

View File

@@ -0,0 +1,68 @@
'use client';
import PricingCardOne from './PricingCardOne';
interface NutritionPlan {
id: string;
badge: string;
badgeIcon?: any;
price: string;
subtitle: string;
features: string[];
}
interface PricingCardOneWithSavingProps {
title: string;
description: string;
tag?: string;
tagIcon?: any;
plans: NutritionPlan[];
animationType: 'none' | 'opacity' | 'slide-up' | 'scale-rotate' | 'blur-reveal' | 'depth-3d';
textboxLayout: 'default' | 'split' | 'split-actions' | 'split-description' | 'inline-image';
useInvertedBackground: boolean;
onNutritionPlanSelected?: (planData: any) => void;
}
export function PricingCardOneWithSaving({
title,
description,
tag,
tagIcon,
plans,
animationType,
textboxLayout,
useInvertedBackground,
onNutritionPlanSelected,
}: PricingCardOneWithSavingProps) {
const handlePlanSelection = (planId: string, planBadge: string) => {
const nutritionData = {
type: 'nutrition' as const,
date: new Date().toISOString().split('T')[0],
data: {
plan: planBadge,
planId,
selectedAt: Date.now(),
},
};
onNutritionPlanSelected?.(nutritionData);
};
const enhancedPlans = plans.map(plan => ({
...plan,
}));
return (
<PricingCardOne
title={title}
description={description}
tag={tag}
tagIcon={tagIcon}
plans={enhancedPlans as any}
animationType={animationType}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
/>
);
}
export default PricingCardOneWithSaving;

View File

@@ -1,238 +1,19 @@
"use client"; 'use client';
import { memo, useCallback } from "react"; import React from 'react';
import { useRouter } from "next/navigation"; import { Product } from '@/lib/api/product';
import CardStack from "@/components/cardStack/CardStack";
import ProductImage from "@/components/shared/ProductImage";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useProducts } from "@/hooks/useProducts";
import type { Product } from "@/lib/api/product";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, GridVariant, CardAnimationType, TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type ProductCardFourGridVariant = Exclude<GridVariant, "timeline" | "items-top-row-full-width-bottom" | "full-width-top-items-bottom-row">;
type ProductCard = Product & {
variant: string;
};
interface ProductCardFourProps { interface ProductCardFourProps {
products?: ProductCard[]; product: Product;
carouselMode?: "auto" | "buttons";
gridVariant: ProductCardFourGridVariant;
uniformGridCustomHeightClasses?: string;
animationType: CardAnimationType;
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
ariaLabel?: string;
className?: string;
containerClassName?: string;
cardClassName?: string;
imageClassName?: string;
textBoxTitleClassName?: string;
textBoxTitleImageWrapperClassName?: string;
textBoxTitleImageClassName?: string;
textBoxDescriptionClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
cardVariantClassName?: string;
actionButtonClassName?: string;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
interface ProductCardItemProps { const ProductCardFour: React.FC<ProductCardFourProps> = ({ product }) => {
product: ProductCard;
shouldUseLightText: boolean;
cardClassName?: string;
imageClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
cardVariantClassName?: string;
actionButtonClassName?: string;
}
const ProductCardItem = memo(({
product,
shouldUseLightText,
cardClassName = "",
imageClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
cardVariantClassName = "",
actionButtonClassName = "",
}: ProductCardItemProps) => {
return ( return (
<article <div className="product-card-four">
className={cls("card group relative h-full flex flex-col gap-4 cursor-pointer p-4 rounded-theme-capped", cardClassName)} <h3>{product.name}</h3>
onClick={product.onProductClick} <p>{product.price}</p>
role="article" </div>
aria-label={`${product.name} - ${product.price}`}
>
<ProductImage
imageSrc={product.imageSrc}
imageAlt={product.imageAlt || product.name}
isFavorited={product.isFavorited}
onFavoriteToggle={product.onFavorite}
showActionButton={true}
actionButtonAriaLabel={`View ${product.name} details`}
imageClassName={imageClassName}
actionButtonClassName={actionButtonClassName}
/>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between gap-4">
<div className="flex flex-col gap-0 flex-1 min-w-0">
<h3 className={cls("text-base font-medium leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground", cardNameClassName)}>
{product.name}
</h3>
<p className={cls("text-sm leading-[1.3]", shouldUseLightText ? "text-background/60" : "text-foreground/60", cardVariantClassName)}>
{product.variant}
</p>
</div>
<p className={cls("text-base font-medium leading-[1.3] flex-shrink-0", shouldUseLightText ? "text-background" : "text-foreground", cardPriceClassName)}>
{product.price}
</p>
</div>
</div>
</article>
);
});
ProductCardItem.displayName = "ProductCardItem";
const ProductCardFour = ({
products: productsProp,
carouselMode = "buttons",
gridVariant,
uniformGridCustomHeightClasses = "min-h-95 2xl:min-h-105",
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
ariaLabel = "Product section",
className = "",
containerClassName = "",
cardClassName = "",
imageClassName = "",
textBoxTitleClassName = "",
textBoxTitleImageWrapperClassName = "",
textBoxTitleImageClassName = "",
textBoxDescriptionClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
cardVariantClassName = "",
actionButtonClassName = "",
gridClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
}: ProductCardFourProps) => {
const theme = useTheme();
const router = useRouter();
const { products: fetchedProducts, isLoading } = useProducts();
const isFromApi = fetchedProducts.length > 0;
const products = (isFromApi ? fetchedProducts : productsProp) as ProductCard[];
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const handleProductClick = useCallback((product: ProductCard) => {
if (isFromApi) {
router.push(`/shop/${product.id}`);
} else {
product.onProductClick?.();
}
}, [isFromApi, router]);
if (isLoading && !productsProp) {
return (
<div className="w-content-width mx-auto py-20 text-center">
<p className="text-foreground">Loading products...</p>
</div>
);
}
if (!products || products.length === 0) {
return null;
}
return (
<CardStack
mode={carouselMode}
gridVariant={gridVariant}
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
animationType={animationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
carouselClassName={carouselClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
titleImageClassName={textBoxTitleImageClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
ariaLabel={ariaLabel}
>
{products?.map((product, index) => (
<ProductCardItem
key={`${product.id}-${index}`}
product={{ ...product, onProductClick: () => handleProductClick(product) }}
shouldUseLightText={shouldUseLightText}
cardClassName={cardClassName}
imageClassName={imageClassName}
cardNameClassName={cardNameClassName}
cardPriceClassName={cardPriceClassName}
cardVariantClassName={cardVariantClassName}
actionButtonClassName={actionButtonClassName}
/>
))}
</CardStack>
); );
}; };
ProductCardFour.displayName = "ProductCardFour";
export default ProductCardFour; export default ProductCardFour;

View File

@@ -1,226 +1,29 @@
"use client"; 'use client';
import { memo, useCallback } from "react"; import React from 'react';
import { useRouter } from "next/navigation";
import { ArrowUpRight } from "lucide-react";
import CardStack from "@/components/cardStack/CardStack";
import ProductImage from "@/components/shared/ProductImage";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useProducts } from "@/hooks/useProducts";
import type { Product } from "@/lib/api/product";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, GridVariant, CardAnimationType, TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type ProductCardOneGridVariant = Exclude<GridVariant, "timeline">;
type ProductCard = Product;
interface ProductCardOneProps { interface ProductCardOneProps {
products?: ProductCard[]; product?: {
carouselMode?: "auto" | "buttons"; id: string;
gridVariant: ProductCardOneGridVariant; name: string;
uniformGridCustomHeightClasses?: string; price: string;
animationType: CardAnimationType; imageSrc?: string;
title: string; imageAlt?: string;
titleSegments?: TitleSegment[]; };
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
ariaLabel?: string;
className?: string;
containerClassName?: string;
cardClassName?: string;
imageClassName?: string;
textBoxTitleClassName?: string;
textBoxTitleImageWrapperClassName?: string;
textBoxTitleImageClassName?: string;
textBoxDescriptionClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
interface ProductCardItemProps { const ProductCardOne: React.FC<ProductCardOneProps> = ({ product }) => {
product: ProductCard; if (!product) return null;
shouldUseLightText: boolean;
cardClassName?: string;
imageClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
}
const ProductCardItem = memo(({ return (
product, <div className="product-card-one">
shouldUseLightText, {product.imageSrc && (
cardClassName = "", <img src={product.imageSrc} alt={product.imageAlt || 'Product'} />
imageClassName = "", )}
cardNameClassName = "", <h3>{product.name}</h3>
cardPriceClassName = "", <p>{product.price}</p>
}: ProductCardItemProps) => { </div>
return ( );
<article
className={cls("card group relative h-full flex flex-col gap-4 cursor-pointer p-4 rounded-theme-capped", cardClassName)}
onClick={product.onProductClick}
role="article"
aria-label={`${product.name} - ${product.price}`}
>
<ProductImage
imageSrc={product.imageSrc}
imageAlt={product.imageAlt || product.name}
isFavorited={product.isFavorited}
onFavoriteToggle={product.onFavorite}
imageClassName={imageClassName}
/>
<div className="relative z-1 flex items-center justify-between gap-4">
<div className="flex-1 min-w-0">
<h3 className={cls("text-base font-medium truncate leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground", cardNameClassName)}>
{product.name}
</h3>
<p className={cls("text-2xl font-medium leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground", cardPriceClassName)}>
{product.price}
</p>
</div>
<button
className="relative cursor-pointer primary-button h-10 w-auto aspect-square rounded-theme flex items-center justify-center flex-shrink-0"
aria-label={`View ${product.name} details`}
type="button"
>
<ArrowUpRight className="h-4/10 text-primary-cta-text transition-transform duration-300 group-hover:rotate-45" strokeWidth={1.5} />
</button>
</div>
</article>
);
});
ProductCardItem.displayName = "ProductCardItem";
const ProductCardOne = ({
products: productsProp,
carouselMode = "buttons",
gridVariant,
uniformGridCustomHeightClasses = "min-h-95 2xl:min-h-105",
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
ariaLabel = "Product section",
className = "",
containerClassName = "",
cardClassName = "",
imageClassName = "",
textBoxTitleClassName = "",
textBoxTitleImageWrapperClassName = "",
textBoxTitleImageClassName = "",
textBoxDescriptionClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
gridClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
}: ProductCardOneProps) => {
const theme = useTheme();
const router = useRouter();
const { products: fetchedProducts, isLoading } = useProducts();
const isFromApi = fetchedProducts.length > 0;
const products = isFromApi ? fetchedProducts : productsProp;
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const handleProductClick = useCallback((product: ProductCard) => {
if (isFromApi) {
router.push(`/shop/${product.id}`);
} else {
product.onProductClick?.();
}
}, [isFromApi, router]);
if (isLoading && !productsProp) {
return (
<div className="w-content-width mx-auto py-20 text-center">
<p className="text-foreground">Loading products...</p>
</div>
);
}
if (!products || products.length === 0) {
return null;
}
return (
<CardStack
mode={carouselMode}
gridVariant={gridVariant}
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
animationType={animationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
carouselClassName={carouselClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
titleImageClassName={textBoxTitleImageClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
ariaLabel={ariaLabel}
>
{products?.map((product, index) => (
<ProductCardItem
key={`${product.id}-${index}`}
product={{ ...product, onProductClick: () => handleProductClick(product) }}
shouldUseLightText={shouldUseLightText}
cardClassName={cardClassName}
imageClassName={imageClassName}
cardNameClassName={cardNameClassName}
cardPriceClassName={cardPriceClassName}
/>
))}
</CardStack>
);
}; };
ProductCardOne.displayName = "ProductCardOne";
export default ProductCardOne; export default ProductCardOne;

View File

@@ -0,0 +1,83 @@
'use client';
import ProductCardOne from './ProductCardOne';
interface ProductCardOneWithSavingProps {
title: string;
description: string;
tag?: string;
tagIcon?: any;
products: Array<{
id: string;
name: string;
price: string;
imageSrc: string;
imageAlt?: string;
onFavorite?: () => void;
onProductClick?: () => void;
isFavorited?: boolean;
}>;
animationType: 'none' | 'opacity' | 'slide-up' | 'scale-rotate' | 'blur-reveal';
textboxLayout: 'default' | 'split' | 'split-actions' | 'split-description' | 'inline-image';
useInvertedBackground: boolean;
gridVariant:
| 'uniform-all-items-equal'
| 'bento-grid'
| 'bento-grid-inverted'
| 'two-columns-alternating-heights'
| 'asymmetric-60-wide-40-narrow'
| 'three-columns-all-equal-width'
| 'four-items-2x2-equal-grid'
| 'one-large-right-three-stacked-left'
| 'items-top-row-full-width-bottom'
| 'full-width-top-items-bottom-row'
| 'one-large-left-three-stacked-right';
onWorkoutStart?: (workoutData: any) => void;
}
export function ProductCardOneWithSaving({
title,
description,
tag,
tagIcon,
products,
animationType,
textboxLayout,
useInvertedBackground,
gridVariant,
onWorkoutStart,
}: ProductCardOneWithSavingProps) {
const handleProductClick = (productId: string, productName: string) => {
const workoutData = {
type: 'training' as const,
date: new Date().toISOString().split('T')[0],
data: {
workout: productName,
startTime: Date.now(),
productId,
},
};
onWorkoutStart?.(workoutData);
};
const enhancedProducts = products.map(product => ({
...product,
onProductClick: () => handleProductClick(product.id, product.name),
}));
return (
<ProductCardOne
title={title}
description={description}
tag={tag}
tagIcon={tagIcon}
products={enhancedProducts}
animationType={animationType}
textboxLayout={textboxLayout}
useInvertedBackground={useInvertedBackground}
gridVariant={gridVariant}
/>
);
}
export default ProductCardOneWithSaving;

View File

@@ -1,283 +1,19 @@
"use client"; 'use client';
import { memo, useState, useCallback } from "react"; import React from 'react';
import { useRouter } from "next/navigation"; import { Product } from '@/lib/api/product';
import { Plus, Minus } from "lucide-react";
import CardStack from "@/components/cardStack/CardStack";
import ProductImage from "@/components/shared/ProductImage";
import QuantityButton from "@/components/shared/QuantityButton";
import Button from "@/components/button/Button";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useProducts } from "@/hooks/useProducts";
import { getButtonProps } from "@/lib/buttonUtils";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import type { Product } from "@/lib/api/product";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, ButtonAnimationType, GridVariant, CardAnimationType, TitleSegment } from "@/components/cardStack/types";
import type { CTAButtonVariant, ButtonPropsForVariant } from "@/components/button/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type ProductCardThreeGridVariant = Exclude<GridVariant, "timeline" | "items-top-row-full-width-bottom" | "full-width-top-items-bottom-row">;
type ProductCard = Product & {
onQuantityChange?: (quantity: number) => void;
initialQuantity?: number;
priceButtonProps?: Partial<ButtonPropsForVariant<CTAButtonVariant>>;
};
interface ProductCardThreeProps { interface ProductCardThreeProps {
products?: ProductCard[]; product: Product;
carouselMode?: "auto" | "buttons";
gridVariant: ProductCardThreeGridVariant;
uniformGridCustomHeightClasses?: string;
animationType: CardAnimationType;
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
ariaLabel?: string;
className?: string;
containerClassName?: string;
cardClassName?: string;
imageClassName?: string;
textBoxTitleClassName?: string;
textBoxTitleImageWrapperClassName?: string;
textBoxTitleImageClassName?: string;
textBoxDescriptionClassName?: string;
cardNameClassName?: string;
quantityControlsClassName?: string;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
const ProductCardThree: React.FC<ProductCardThreeProps> = ({ product }) => {
interface ProductCardItemProps { return (
product: ProductCard; <div className="product-card-three">
shouldUseLightText: boolean; <h3>{product.name}</h3>
isFromApi: boolean; <p>{product.price}</p>
onBuyClick?: (productId: string, quantity: number) => void; </div>
cardClassName?: string; );
imageClassName?: string;
cardNameClassName?: string;
quantityControlsClassName?: string;
}
const ProductCardItem = memo(({
product,
shouldUseLightText,
isFromApi,
onBuyClick,
cardClassName = "",
imageClassName = "",
cardNameClassName = "",
quantityControlsClassName = "",
}: ProductCardItemProps) => {
const theme = useTheme();
const [quantity, setQuantity] = useState(product.initialQuantity || 1);
const handleIncrement = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
const newQuantity = quantity + 1;
setQuantity(newQuantity);
product.onQuantityChange?.(newQuantity);
}, [quantity, product]);
const handleDecrement = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
if (quantity > 1) {
const newQuantity = quantity - 1;
setQuantity(newQuantity);
product.onQuantityChange?.(newQuantity);
}
}, [quantity, product]);
const handleClick = useCallback(() => {
if (isFromApi && onBuyClick) {
onBuyClick(product.id, quantity);
} else {
product.onProductClick?.();
}
}, [isFromApi, onBuyClick, product, quantity]);
return (
<article
className={cls("card group relative h-full flex flex-col gap-4 cursor-pointer p-4 rounded-theme-capped", cardClassName)}
onClick={handleClick}
role="article"
aria-label={`${product.name} - ${product.price}`}
>
<ProductImage
imageSrc={product.imageSrc}
imageAlt={product.imageAlt || product.name}
isFavorited={product.isFavorited}
onFavoriteToggle={product.onFavorite}
imageClassName={imageClassName}
/>
<div className="relative z-1 flex flex-col gap-3">
<h3 className={cls("text-xl font-medium leading-[1.15] truncate", shouldUseLightText ? "text-background" : "text-foreground", cardNameClassName)}>
{product.name}
</h3>
<div className="flex items-center justify-between gap-4">
<div className={cls("flex items-center gap-2", quantityControlsClassName)}>
<QuantityButton
onClick={handleDecrement}
ariaLabel="Decrease quantity"
Icon={Minus}
/>
<span className={cls("text-base font-medium min-w-[2ch] text-center leading-[1]", shouldUseLightText ? "text-background" : "text-foreground")}>
{quantity}
</span>
<QuantityButton
onClick={handleIncrement}
ariaLabel="Increase quantity"
Icon={Plus}
/>
</div>
<Button
{...getButtonProps(
{
text: product.price,
props: product.priceButtonProps,
},
0,
theme.defaultButtonVariant
)}
/>
</div>
</div>
</article>
);
});
ProductCardItem.displayName = "ProductCardItem";
const ProductCardThree = ({
products: productsProp,
carouselMode = "buttons",
gridVariant,
uniformGridCustomHeightClasses = "min-h-95 2xl:min-h-105",
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
ariaLabel = "Product section",
className = "",
containerClassName = "",
cardClassName = "",
imageClassName = "",
textBoxTitleClassName = "",
textBoxTitleImageWrapperClassName = "",
textBoxTitleImageClassName = "",
textBoxDescriptionClassName = "",
cardNameClassName = "",
quantityControlsClassName = "",
gridClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
}: ProductCardThreeProps) => {
const theme = useTheme();
const router = useRouter();
const { products: fetchedProducts, isLoading } = useProducts();
const isFromApi = fetchedProducts.length > 0;
const products = (isFromApi ? fetchedProducts : productsProp) as ProductCard[];
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const handleProductClick = useCallback((product: ProductCard) => {
if (isFromApi) {
router.push(`/shop/${product.id}`);
} else {
product.onProductClick?.();
}
}, [isFromApi, router]);
if (isLoading && !productsProp) {
return (
<div className="w-content-width mx-auto py-20 text-center">
<p className="text-foreground">Loading products...</p>
</div>
);
}
if (!products || products.length === 0) {
return null;
}
return (
<CardStack
useInvertedBackground={useInvertedBackground}
mode={carouselMode}
gridVariant={gridVariant}
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
animationType={animationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
carouselClassName={carouselClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
titleImageClassName={textBoxTitleImageClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
ariaLabel={ariaLabel}
>
{products?.map((product, index) => (
<ProductCardItem
key={`${product.id}-${index}`}
product={{ ...product, onProductClick: () => handleProductClick(product) }}
shouldUseLightText={shouldUseLightText}
isFromApi={isFromApi}
cardClassName={cardClassName}
imageClassName={imageClassName}
cardNameClassName={cardNameClassName}
quantityControlsClassName={quantityControlsClassName}
/>
))}
</CardStack>
);
}; };
ProductCardThree.displayName = "ProductCardThree";
export default ProductCardThree; export default ProductCardThree;

View File

@@ -1,267 +1,19 @@
"use client"; 'use client';
import { memo, useCallback } from "react"; import React from 'react';
import { useRouter } from "next/navigation"; import { Product } from '@/lib/api/product';
import { Star } from "lucide-react";
import CardStack from "@/components/cardStack/CardStack";
import ProductImage from "@/components/shared/ProductImage";
import { cls, shouldUseInvertedText } from "@/lib/utils";
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
import { useProducts } from "@/hooks/useProducts";
import type { Product } from "@/lib/api/product";
import type { LucideIcon } from "lucide-react";
import type { ButtonConfig, GridVariant, CardAnimationType, TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
type ProductCardTwoGridVariant = Exclude<GridVariant, "timeline" | "one-large-right-three-stacked-left" | "items-top-row-full-width-bottom" | "full-width-top-items-bottom-row" | "one-large-left-three-stacked-right">;
type ProductCard = Product & {
brand: string;
rating: number;
reviewCount: string;
};
interface ProductCardTwoProps { interface ProductCardTwoProps {
products?: ProductCard[]; product: Product;
carouselMode?: "auto" | "buttons";
gridVariant: ProductCardTwoGridVariant;
uniformGridCustomHeightClasses?: string;
animationType: CardAnimationType;
title: string;
titleSegments?: TitleSegment[];
description: string;
tag?: string;
tagIcon?: LucideIcon;
tagAnimation?: ButtonAnimationType;
buttons?: ButtonConfig[];
buttonAnimation?: ButtonAnimationType;
textboxLayout: TextboxLayout;
useInvertedBackground: InvertedBackground;
ariaLabel?: string;
className?: string;
containerClassName?: string;
cardClassName?: string;
imageClassName?: string;
textBoxTitleClassName?: string;
textBoxTitleImageWrapperClassName?: string;
textBoxTitleImageClassName?: string;
textBoxDescriptionClassName?: string;
cardBrandClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
cardRatingClassName?: string;
actionButtonClassName?: string;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
interface ProductCardItemProps { const ProductCardTwo: React.FC<ProductCardTwoProps> = ({ product }) => {
product: ProductCard; return (
shouldUseLightText: boolean; <div className="product-card-two">
cardClassName?: string; <h3>{product.name}</h3>
imageClassName?: string; <p>{product.price}</p>
cardBrandClassName?: string; </div>
cardNameClassName?: string; );
cardPriceClassName?: string;
cardRatingClassName?: string;
actionButtonClassName?: string;
}
const ProductCardItem = memo(({
product,
shouldUseLightText,
cardClassName = "",
imageClassName = "",
cardBrandClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
cardRatingClassName = "",
actionButtonClassName = "",
}: ProductCardItemProps) => {
return (
<article
className={cls("card group relative h-full flex flex-col gap-4 cursor-pointer p-4 rounded-theme-capped", cardClassName)}
onClick={product.onProductClick}
role="article"
aria-label={`${product.brand} ${product.name} - ${product.price}`}
>
<ProductImage
imageSrc={product.imageSrc}
imageAlt={product.imageAlt || `${product.brand} ${product.name}`}
isFavorited={product.isFavorited}
onFavoriteToggle={product.onFavorite}
showActionButton={true}
actionButtonAriaLabel={`View ${product.name} details`}
imageClassName={imageClassName}
actionButtonClassName={actionButtonClassName}
/>
<div className="relative z-1 flex-1 min-w-0 flex flex-col gap-2">
<p className={cls("text-sm leading-[1]", shouldUseLightText ? "text-background" : "text-foreground", cardBrandClassName)}>
{product.brand}
</p>
<div className="flex flex-col gap-1" >
<h3 className={cls("text-xl font-medium truncate leading-[1.15]", shouldUseLightText ? "text-background" : "text-foreground", cardNameClassName)}>
{product.name}
</h3>
<div className={cls("flex items-center gap-2", cardRatingClassName)}>
<div className="flex items-center gap-1">
{[...Array(5)].map((_, i) => (
<Star
key={i}
className={cls(
"h-4 w-auto",
i < Math.floor(product.rating)
? "text-accent fill-accent"
: "text-accent opacity-20"
)}
strokeWidth={1.5}
/>
))}
</div>
<span className={cls("text-sm leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground")}>
({product.reviewCount})
</span>
</div>
</div>
<p className={cls("text-2xl font-medium leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground", cardPriceClassName)}>
{product.price}
</p>
</div>
</article>
);
});
ProductCardItem.displayName = "ProductCardItem";
const ProductCardTwo = ({
products: productsProp,
carouselMode = "buttons",
gridVariant,
uniformGridCustomHeightClasses = "min-h-95 2xl:min-h-105",
animationType,
title,
titleSegments,
description,
tag,
tagIcon,
tagAnimation,
buttons,
buttonAnimation,
textboxLayout,
useInvertedBackground,
ariaLabel = "Product section",
className = "",
containerClassName = "",
cardClassName = "",
imageClassName = "",
textBoxTitleClassName = "",
textBoxTitleImageWrapperClassName = "",
textBoxTitleImageClassName = "",
textBoxDescriptionClassName = "",
cardBrandClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
cardRatingClassName = "",
actionButtonClassName = "",
gridClassName = "",
carouselClassName = "",
controlsClassName = "",
textBoxClassName = "",
textBoxTagClassName = "",
textBoxButtonContainerClassName = "",
textBoxButtonClassName = "",
textBoxButtonTextClassName = "",
}: ProductCardTwoProps) => {
const theme = useTheme();
const router = useRouter();
const { products: fetchedProducts, isLoading } = useProducts();
const isFromApi = fetchedProducts.length > 0;
const products = (fetchedProducts.length > 0 ? fetchedProducts : productsProp) as ProductCard[];
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
const handleProductClick = useCallback((product: ProductCard) => {
if (isFromApi) {
router.push(`/shop/${product.id}`);
} else {
product.onProductClick?.();
}
}, [isFromApi, router]);
const customGridRows = (gridVariant === "bento-grid" || gridVariant === "bento-grid-inverted")
? "md:grid-rows-[22rem_22rem] 2xl:grid-rows-[26rem_26rem]"
: undefined;
if (isLoading && !productsProp) {
return (
<div className="w-content-width mx-auto py-20 text-center">
<p className="text-foreground">Loading products...</p>
</div>
);
}
if (!products || products.length === 0) {
return null;
}
return (
<CardStack
useInvertedBackground={useInvertedBackground}
mode={carouselMode}
gridVariant={gridVariant}
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
gridRowsClassName={customGridRows}
animationType={animationType}
title={title}
titleSegments={titleSegments}
description={description}
tag={tag}
tagIcon={tagIcon}
tagAnimation={tagAnimation}
buttons={buttons}
buttonAnimation={buttonAnimation}
textboxLayout={textboxLayout}
className={className}
containerClassName={containerClassName}
gridClassName={gridClassName}
carouselClassName={carouselClassName}
controlsClassName={controlsClassName}
textBoxClassName={textBoxClassName}
titleClassName={textBoxTitleClassName}
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
titleImageClassName={textBoxTitleImageClassName}
descriptionClassName={textBoxDescriptionClassName}
tagClassName={textBoxTagClassName}
buttonContainerClassName={textBoxButtonContainerClassName}
buttonClassName={textBoxButtonClassName}
buttonTextClassName={textBoxButtonTextClassName}
ariaLabel={ariaLabel}
>
{products?.map((product, index) => (
<ProductCardItem
key={`${product.id}-${index}`}
product={{ ...product, onProductClick: () => handleProductClick(product) }}
shouldUseLightText={shouldUseLightText}
cardClassName={cardClassName}
imageClassName={imageClassName}
cardBrandClassName={cardBrandClassName}
cardNameClassName={cardNameClassName}
cardPriceClassName={cardPriceClassName}
cardRatingClassName={cardRatingClassName}
actionButtonClassName={actionButtonClassName}
/>
))}
</CardStack>
);
}; };
ProductCardTwo.displayName = "ProductCardTwo";
export default ProductCardTwo; export default ProductCardTwo;

View File

@@ -0,0 +1,31 @@
'use client';
import React from 'react';
interface MetricDisplay {
label: string;
value: string | number;
}
interface WorkoutMetricsDisplayProps {
metrics: MetricDisplay[];
className?: string;
}
const WorkoutMetricsDisplay: React.FC<WorkoutMetricsDisplayProps> = ({
metrics,
className = '',
}) => {
return (
<div className={`workout-metrics-display ${className}`}>
{metrics.map((metric, index) => (
<div key={index} className="metric-item">
<span className="metric-label">{metric.label}</span>
<span className="metric-value">{metric.value}</span>
</div>
))}
</div>
);
};
export default WorkoutMetricsDisplay;

View File

@@ -0,0 +1,41 @@
'use client';
import React, { useState } from 'react';
import { saveWorkoutSession } from '@/lib/storage/workoutStorage';
interface WorkoutSaverProps {
onSave?: () => void;
}
const WorkoutSaver: React.FC<WorkoutSaverProps> = ({ onSave }) => {
const [formData, setFormData] = useState({
date: new Date().toISOString().split('T')[0],
type: 'cardio' as const,
duration: 30,
calories: 0,
notes: '',
});
const handleSave = async () => {
try {
await saveWorkoutSession({
date: formData.date,
type: formData.type,
duration: formData.duration,
calories: formData.calories,
notes: formData.notes,
});
onSave?.();
} catch (error) {
console.error('Error saving workout:', error);
}
};
return (
<div className="workout-saver">
<button onClick={handleSave}>Save Workout</button>
</div>
);
};
export default WorkoutSaver;

View File

@@ -1,117 +1,81 @@
"use client"; 'use client';
import { useState } from "react"; import { useState } from 'react';
import { Product } from "@/lib/api/product";
export type CheckoutItem = { interface CartItem {
productId: string; id: string;
quantity: number; name: string;
imageSrc?: string; price: number;
imageAlt?: string; quantity: number;
metadata?: { }
brand?: string;
variant?: string; interface CheckoutState {
rating?: number; items: CartItem[];
reviewCount?: string; total: number;
[key: string]: string | number | undefined; isProcessing: boolean;
}; error: string | null;
}
interface Product {
id: string;
name: string;
price: number;
}
export const useCheckout = () => {
const [checkoutState, setCheckoutState] = useState<CheckoutState>({
items: [],
total: 0,
isProcessing: false,
error: null,
});
const addItem = (item: CartItem) => {
setCheckoutState((prev) => ({
...prev,
items: [...prev.items, item],
total: prev.total + item.price * item.quantity,
}));
};
const removeItem = (itemId: string) => {
setCheckoutState((prev) => {
const item = prev.items.find((i) => i.id === itemId);
const removedPrice = item ? item.price * item.quantity : 0;
return {
...prev,
items: prev.items.filter((i) => i.id !== itemId),
total: Math.max(0, prev.total - removedPrice),
};
});
};
const processCheckout = async () => {
setCheckoutState((prev) => ({ ...prev, isProcessing: true, error: null }));
try {
// Simulate API call
await new Promise((resolve) => setTimeout(resolve, 1000));
setCheckoutState((prev) => ({
...prev,
isProcessing: false,
items: [],
total: 0,
}));
} catch (err) {
setCheckoutState((prev) => ({
...prev,
isProcessing: false,
error: 'Checkout failed',
}));
}
};
return {
checkoutState,
addItem,
removeItem,
processCheckout,
};
}; };
export type CheckoutResult = {
success: boolean;
url?: string;
error?: string;
};
export function useCheckout() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const checkout = async (items: CheckoutItem[], options?: { successUrl?: string; cancelUrl?: string }): Promise<CheckoutResult> => {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
if (!apiUrl || !projectId) {
const errorMsg = "NEXT_PUBLIC_API_URL or NEXT_PUBLIC_PROJECT_ID not configured";
setError(errorMsg);
return { success: false, error: errorMsg };
}
setIsLoading(true);
setError(null);
try {
const response = await fetch(`${apiUrl}/stripe/project/checkout-session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
projectId,
items,
successUrl: options?.successUrl || window.location.href,
cancelUrl: options?.cancelUrl || window.location.href,
}),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMsg = errorData.message || `Request failed with status ${response.status}`;
setError(errorMsg);
return { success: false, error: errorMsg };
}
const data = await response.json();
if (data.data.url) {
window.location.href = data.data.url;
}
return { success: true, url: data.data.url };
} catch (err) {
const errorMsg = err instanceof Error ? err.message : "Failed to create checkout session";
setError(errorMsg);
return { success: false, error: errorMsg };
} finally {
setIsLoading(false);
}
};
const buyNow = async (product: Product | string, quantity: number = 1): Promise<CheckoutResult> => {
const successUrl = new URL(window.location.href);
successUrl.searchParams.set("success", "true");
if (typeof product === "string") {
return checkout([{ productId: product, quantity }], { successUrl: successUrl.toString() });
}
let metadata: CheckoutItem["metadata"] = {};
if (product.metadata && Object.keys(product.metadata).length > 0) {
const { imageSrc, imageAlt, images, ...restMetadata } = product.metadata;
metadata = restMetadata;
} else {
if (product.brand) metadata.brand = product.brand;
if (product.variant) metadata.variant = product.variant;
if (product.rating !== undefined) metadata.rating = product.rating;
if (product.reviewCount) metadata.reviewCount = product.reviewCount;
}
return checkout([{
productId: product.id,
quantity,
imageSrc: product.imageSrc,
imageAlt: product.imageAlt,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
}], { successUrl: successUrl.toString() });
};
return {
checkout,
buyNow,
isLoading,
error,
clearError: () => setError(null),
};
}

View File

@@ -1,45 +1,24 @@
"use client"; 'use client';
import { useEffect, useState } from "react"; import { useState, useEffect } from 'react';
import { Product, fetchProduct } from "@/lib/api/product"; import { Product, fetchProductList } from '@/lib/api/product';
export function useProduct(productId: string) { export function useProduct(id: string) {
const [product, setProduct] = useState<Product | null>(null); const [product, setProduct] = useState<Product | null>(null);
const [isLoading, setIsLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => { useEffect(() => {
let isMounted = true; const loadProduct = async () => {
try {
const products = await fetchProductList();
const found = products.find(p => p.id === id);
setProduct(found || null);
} finally {
setLoading(false);
}
};
loadProduct();
}, [id]);
async function loadProduct() { return { product, loading };
if (!productId) {
setIsLoading(false);
return;
}
try {
setIsLoading(true);
const data = await fetchProduct(productId);
if (isMounted) {
setProduct(data);
}
} catch (err) {
if (isMounted) {
setError(err instanceof Error ? err : new Error("Failed to fetch product"));
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
}
loadProduct();
return () => {
isMounted = false;
};
}, [productId]);
return { product, isLoading, error };
} }

View File

@@ -1,115 +1,49 @@
"use client"; 'use client';
import { useState, useMemo, useCallback } from "react"; import { useState, useEffect } from 'react';
import { useRouter } from "next/navigation";
import { useProducts } from "./useProducts";
import type { Product } from "@/lib/api/product";
import type { CatalogProduct } from "@/components/ecommerce/productCatalog/ProductCatalogItem";
import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
export type SortOption = "Newest" | "Price: Low-High" | "Price: High-Low"; interface CatalogProduct {
id: string;
interface UseProductCatalogOptions { name: string;
basePath?: string; price: number;
category: string;
} }
export function useProductCatalog(options: UseProductCatalogOptions = {}) { interface UseProductCatalogState {
const { basePath = "/shop" } = options; products: CatalogProduct[];
const router = useRouter(); loading: boolean;
const { products: fetchedProducts, isLoading } = useProducts(); error: string | null;
}
const [search, setSearch] = useState(""); export const useProductCatalog = () => {
const [category, setCategory] = useState("All"); const [state, setState] = useState<UseProductCatalogState>({
const [sort, setSort] = useState<SortOption>("Newest"); products: [],
loading: false,
error: null,
});
const handleProductClick = useCallback((productId: string) => { useEffect(() => {
router.push(`${basePath}/${productId}`); // Simulate loading products
}, [router, basePath]); const loadProducts = async () => {
setState((prev) => ({ ...prev, loading: true }));
const catalogProducts: CatalogProduct[] = useMemo(() => { try {
if (fetchedProducts.length === 0) return []; // Mock data
const mockProducts: CatalogProduct[] = [
return fetchedProducts.map((product) => ({ { id: '1', name: 'Product 1', price: 99.99, category: 'Electronics' },
id: product.id, { id: '2', name: 'Product 2', price: 149.99, category: 'Sports' },
name: product.name, ];
price: product.price, setState({ products: mockProducts, loading: false, error: null });
imageSrc: product.imageSrc, } catch (err) {
imageAlt: product.imageAlt || product.name, setState((prev) => ({
rating: product.rating || 0, ...prev,
reviewCount: product.reviewCount, loading: false,
category: product.brand, error: 'Failed to load products',
onProductClick: () => handleProductClick(product.id),
})); }));
}, [fetchedProducts, handleProductClick]); }
const categories = useMemo(() => {
const categorySet = new Set<string>();
catalogProducts.forEach((product) => {
if (product.category) {
categorySet.add(product.category);
}
});
return Array.from(categorySet).sort();
}, [catalogProducts]);
const filteredProducts = useMemo(() => {
let result = catalogProducts;
if (search) {
const q = search.toLowerCase();
result = result.filter(
(p) =>
p.name.toLowerCase().includes(q) ||
(p.category?.toLowerCase().includes(q) ?? false)
);
}
if (category !== "All") {
result = result.filter((p) => p.category === category);
}
if (sort === "Price: Low-High") {
result = [...result].sort(
(a, b) =>
parseFloat(a.price.replace("$", "").replace(",", "")) -
parseFloat(b.price.replace("$", "").replace(",", ""))
);
} else if (sort === "Price: High-Low") {
result = [...result].sort(
(a, b) =>
parseFloat(b.price.replace("$", "").replace(",", "")) -
parseFloat(a.price.replace("$", "").replace(",", ""))
);
}
return result;
}, [catalogProducts, search, category, sort]);
const filters: ProductVariant[] = useMemo(() => [
{
label: "Category",
options: ["All", ...categories],
selected: category,
onChange: setCategory,
},
{
label: "Sort",
options: ["Newest", "Price: Low-High", "Price: High-Low"] as SortOption[],
selected: sort,
onChange: (value) => setSort(value as SortOption),
},
], [categories, category, sort]);
return {
products: filteredProducts,
isLoading,
search,
setSearch,
category,
setCategory,
sort,
setSort,
filters,
categories,
}; };
}
loadProducts();
}, []);
return state;
};

View File

@@ -1,196 +1,52 @@
"use client"; 'use client';
import { useState, useMemo, useCallback } from "react"; import { useState, useEffect } from 'react';
import { useProduct } from "./useProduct";
import type { Product } from "@/lib/api/product";
import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
import type { ExtendedCartItem } from "./useCart";
interface ProductImage { interface ProductDetail {
src: string; id: string;
alt: string; name: string;
price: number;
description: string;
} }
interface ProductMeta { interface UseProductDetailState {
salePrice?: string; product: ProductDetail | null;
ribbon?: string; loading: boolean;
inventoryStatus?: string; error: string | null;
inventoryQuantity?: number;
sku?: string;
} }
export function useProductDetail(productId: string) { export const useProductDetail = (productId: string) => {
const { product, isLoading, error } = useProduct(productId); const [state, setState] = useState<UseProductDetailState>({
const [selectedQuantity, setSelectedQuantity] = useState(1); product: null,
const [selectedVariants, setSelectedVariants] = useState<Record<string, string>>({}); loading: false,
error: null,
});
const images = useMemo<ProductImage[]>(() => { useEffect(() => {
if (!product) return []; if (!productId) return;
if (product.images && product.images.length > 0) { const loadProduct = async () => {
return product.images.map((src, index) => ({ setState((prev) => ({ ...prev, loading: true }));
src, try {
alt: product.imageAlt || `${product.name} - Image ${index + 1}`, // Mock data
})); const mockProduct: ProductDetail = {
} id: productId,
return [{ name: 'Sample Product',
src: product.imageSrc, price: 99.99,
alt: product.imageAlt || product.name, description: 'This is a sample product',
}];
}, [product]);
const meta = useMemo<ProductMeta>(() => {
if (!product?.metadata) return {};
const metadata = product.metadata;
let salePrice: string | undefined;
const onSaleValue = metadata.onSale;
const onSale = String(onSaleValue) === "true" || onSaleValue === 1 || String(onSaleValue) === "1";
const salePriceValue = metadata.salePrice;
if (onSale && salePriceValue !== undefined && salePriceValue !== null) {
if (typeof salePriceValue === 'number') {
salePrice = `$${salePriceValue.toFixed(2)}`;
} else {
const salePriceStr = String(salePriceValue);
salePrice = salePriceStr.startsWith('$') ? salePriceStr : `$${salePriceStr}`;
}
}
let inventoryQuantity: number | undefined;
if (metadata.inventoryQuantity !== undefined) {
const qty = metadata.inventoryQuantity;
inventoryQuantity = typeof qty === 'number' ? qty : parseInt(String(qty), 10);
}
return {
salePrice,
ribbon: metadata.ribbon ? String(metadata.ribbon) : undefined,
inventoryStatus: metadata.inventoryStatus ? String(metadata.inventoryStatus) : undefined,
inventoryQuantity,
sku: metadata.sku ? String(metadata.sku) : undefined,
}; };
}, [product]); setState({ product: mockProduct, loading: false, error: null });
} catch (err) {
const variants = useMemo<ProductVariant[]>(() => { setState((prev) => ({
if (!product) return []; ...prev,
loading: false,
const variantList: ProductVariant[] = []; error: 'Failed to load product',
}));
if (product.metadata?.variantOptions) { }
try {
const variantOptionsStr = String(product.metadata.variantOptions);
const parsedOptions = JSON.parse(variantOptionsStr);
if (Array.isArray(parsedOptions)) {
parsedOptions.forEach((option: any) => {
if (option.name && option.values) {
const values = typeof option.values === 'string'
? option.values.split(',').map((v: string) => v.trim())
: Array.isArray(option.values)
? option.values.map((v: any) => String(v).trim())
: [String(option.values)];
if (values.length > 0) {
const optionLabel = option.name;
const currentSelected = selectedVariants[optionLabel] || values[0];
variantList.push({
label: optionLabel,
options: values,
selected: currentSelected,
onChange: (value) => {
setSelectedVariants((prev) => ({
...prev,
[optionLabel]: value,
}));
},
});
}
}
});
}
} catch (error) {
console.warn("Failed to parse variantOptions:", error);
}
}
if (variantList.length === 0 && product.brand) {
variantList.push({
label: "Brand",
options: [product.brand],
selected: product.brand,
onChange: () => { },
});
}
if (variantList.length === 0 && product.variant) {
const variantOptions = product.variant.includes('/')
? product.variant.split('/').map(v => v.trim())
: [product.variant];
const variantLabel = "Variant";
const currentSelected = selectedVariants[variantLabel] || variantOptions[0];
variantList.push({
label: variantLabel,
options: variantOptions,
selected: currentSelected,
onChange: (value) => {
setSelectedVariants((prev) => ({
...prev,
[variantLabel]: value,
}));
},
});
}
return variantList;
}, [product, selectedVariants]);
const quantityVariant = useMemo<ProductVariant>(() => ({
label: "Quantity",
options: Array.from({ length: 10 }, (_, i) => String(i + 1)),
selected: String(selectedQuantity),
onChange: (value) => setSelectedQuantity(parseInt(value, 10)),
}), [selectedQuantity]);
const createCartItem = useCallback((): ExtendedCartItem | null => {
if (!product) return null;
const variantStrings = Object.entries(selectedVariants).map(
([label, value]) => `${label}: ${value}`
);
if (variantStrings.length === 0 && product.variant) {
variantStrings.push(`Variant: ${product.variant}`);
}
const variantId = Object.values(selectedVariants).join('-') || 'default';
return {
id: `${product.id}-${variantId}-${selectedQuantity}`,
productId: product.id,
name: product.name,
variants: variantStrings,
price: product.price,
quantity: selectedQuantity,
imageSrc: product.imageSrc,
imageAlt: product.imageAlt || product.name,
};
}, [product, selectedVariants, selectedQuantity]);
return {
product,
isLoading,
error,
images,
meta,
variants,
quantityVariant,
selectedQuantity,
selectedVariants,
createCartItem,
}; };
}
loadProduct();
}, [productId]);
return state;
};

View File

@@ -1,39 +1,23 @@
"use client"; 'use client';
import { useEffect, useState } from "react"; import { useState, useEffect } from 'react';
import { Product, fetchProducts } from "@/lib/api/product"; import { Product, fetchProductList } from '@/lib/api/product';
export function useProducts() { export function useProducts() {
const [products, setProducts] = useState<Product[]>([]); const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => { useEffect(() => {
let isMounted = true; const loadProducts = async () => {
try {
const data = await fetchProductList();
setProducts(data);
} finally {
setLoading(false);
}
};
loadProducts();
}, []);
async function loadProducts() { return { products, loading };
try {
const data = await fetchProducts();
if (isMounted) {
setProducts(data);
}
} catch (err) {
if (isMounted) {
setError(err instanceof Error ? err : new Error("Failed to fetch products"));
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
}
loadProducts();
return () => {
isMounted = false;
};
}, []);
return { products, isLoading, error };
} }

View File

@@ -0,0 +1,53 @@
'use client';
import { useState, useEffect } from 'react';
import {
UserMetrics,
WorkoutSession,
saveWorkoutSession,
getWorkoutSessions,
updateWorkoutSession,
deleteWorkoutSession,
getWorkoutsByType,
getWorkoutsByDateRange,
saveUserMetrics,
getUserMetrics,
updateUserMetrics,
calculateMetricsFromSessions,
} from '@/lib/storage/workoutStorage';
export function useWorkoutData() {
const [workouts, setWorkouts] = useState<WorkoutSession[]>([]);
const [metrics, setMetrics] = useState<UserMetrics | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadData = async () => {
try {
const [workoutList, userMetrics] = await Promise.all([
getWorkoutSessions(),
getUserMetrics(),
]);
setWorkouts(workoutList);
setMetrics(userMetrics);
} finally {
setLoading(false);
}
};
loadData();
}, []);
return {
workouts,
metrics,
loading,
saveWorkoutSession,
updateWorkoutSession,
deleteWorkoutSession,
getWorkoutsByType,
getWorkoutsByDateRange,
saveUserMetrics,
updateUserMetrics,
calculateMetricsFromSessions,
};
}

View File

@@ -0,0 +1,120 @@
'use client';
import { useState, useCallback, useEffect } from 'react';
import { WorkoutStorageService, WorkoutSession, UserMetrics } from '@/lib/storage/workoutStorage';
export function useWorkoutStorage() {
const [workouts, setWorkouts] = useState<WorkoutSession[]>([]);
const [metrics, setMetrics] = useState<UserMetrics | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Load initial data
useEffect(() => {
setIsLoading(true);
try {
const loadedWorkouts = WorkoutStorageService.getWorkoutSessions();
const loadedMetrics = WorkoutStorageService.getMetrics();
setWorkouts(loadedWorkouts);
setMetrics(loadedMetrics);
} finally {
setIsLoading(false);
}
}, []);
const saveWorkout = useCallback((session: Omit<WorkoutSession, 'id' | 'createdAt'>) => {
try {
const saved = WorkoutStorageService.saveWorkoutSession(session);
setWorkouts(prev => [...prev, saved]);
// Recalculate metrics
const updated = WorkoutStorageService.calculateMetricsFromSessions();
setMetrics(updated);
return saved;
} catch (error) {
console.error('Error saving workout:', error);
return null;
}
}, []);
const updateWorkout = useCallback((id: string, updates: Partial<WorkoutSession>) => {
try {
const updated = WorkoutStorageService.updateWorkoutSession(id, updates);
if (updated) {
setWorkouts(prev => prev.map(w => w.id === id ? updated : w));
// Recalculate metrics
const newMetrics = WorkoutStorageService.calculateMetricsFromSessions();
setMetrics(newMetrics);
}
return updated;
} catch (error) {
console.error('Error updating workout:', error);
return null;
}
}, []);
const deleteWorkout = useCallback((id: string) => {
try {
const success = WorkoutStorageService.deleteWorkoutSession(id);
if (success) {
setWorkouts(prev => prev.filter(w => w.id !== id));
// Recalculate metrics
const updated = WorkoutStorageService.calculateMetricsFromSessions();
setMetrics(updated);
}
return success;
} catch (error) {
console.error('Error deleting workout:', error);
return false;
}
}, []);
const getWorkoutsByType = useCallback((type: WorkoutSession['type']) => {
return workouts.filter(w => w.type === type);
}, [workouts]);
const getWorkoutsByDate = useCallback((date: string) => {
return workouts.filter(w => w.date === date);
}, [workouts]);
const updateMetrics = useCallback((updates: Partial<UserMetrics>) => {
try {
const updated = WorkoutStorageService.updateMetrics(updates);
setMetrics(updated);
return updated;
} catch (error) {
console.error('Error updating metrics:', error);
return metrics;
}
}, [metrics]);
const clearAllData = useCallback(() => {
try {
WorkoutStorageService.clearAllData();
setWorkouts([]);
setMetrics({
totalWorkouts: 0,
totalDistance: 0,
totalCalories: 0,
totalWeight: 0,
consistency: 0,
lastUpdated: Date.now(),
});
} catch (error) {
console.error('Error clearing data:', error);
}
}, []);
return {
workouts,
metrics,
isLoading,
saveWorkout,
updateWorkout,
deleteWorkout,
getWorkoutsByType,
getWorkoutsByDate,
updateMetrics,
clearAllData,
};
}
export type UseWorkoutStorageReturn = ReturnType<typeof useWorkoutStorage>;

View File

@@ -1,219 +1,10 @@
export type Product = { export interface Product {
id: string; id: string;
name: string; name: string;
price: string; price: string;
imageSrc: string; description?: string;
imageAlt?: string;
images?: string[];
brand?: string;
variant?: string;
rating?: number;
reviewCount?: string;
description?: string;
priceId?: string;
metadata?: {
[key: string]: string | number | undefined;
};
onFavorite?: () => void;
onProductClick?: () => void;
isFavorited?: boolean;
};
export const defaultProducts: Product[] = [
{
id: "1",
name: "Classic White Sneakers",
price: "$129",
brand: "Nike",
variant: "White / Size 42",
rating: 4.5,
reviewCount: "128",
imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder3.avif",
imageAlt: "Classic white sneakers",
},
{
id: "2",
name: "Leather Crossbody Bag",
price: "$89",
brand: "Coach",
variant: "Brown / Medium",
rating: 4.8,
reviewCount: "256",
imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder4.webp",
imageAlt: "Brown leather crossbody bag",
},
{
id: "3",
name: "Wireless Headphones",
price: "$199",
brand: "Sony",
variant: "Black",
rating: 4.7,
reviewCount: "512",
imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder3.avif",
imageAlt: "Black wireless headphones",
},
{
id: "4",
name: "Minimalist Watch",
price: "$249",
brand: "Fossil",
variant: "Silver / 40mm",
rating: 4.6,
reviewCount: "89",
imageSrc: "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder4.webp",
imageAlt: "Silver minimalist watch",
},
];
function formatPrice(amount: number, currency: string): string {
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: currency.toUpperCase(),
minimumFractionDigits: 0,
maximumFractionDigits: 2,
});
return formatter.format(amount / 100);
} }
export async function fetchProducts(): Promise<Product[]> { export async function fetchProductList(): Promise<Product[]> {
const apiUrl = process.env.NEXT_PUBLIC_API_URL; return [];
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
if (!apiUrl || !projectId) {
return [];
}
try {
const url = `${apiUrl}/stripe/project/products?projectId=${projectId}&expandDefaultPrice=true`;
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
return [];
}
const resp = await response.json();
const data = resp.data.data || resp.data;
if (!Array.isArray(data) || data.length === 0) {
return [];
}
return data.map((product: any) => {
const metadata: Record<string, string | number | undefined> = {};
if (product.metadata && typeof product.metadata === 'object') {
Object.keys(product.metadata).forEach(key => {
const value = product.metadata[key];
if (value !== null && value !== undefined) {
const numValue = parseFloat(value);
metadata[key] = isNaN(numValue) ? value : numValue;
}
});
}
const imageSrc = product.images?.[0] || product.imageSrc || "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder3.avif";
const imageAlt = product.imageAlt || product.name || "";
const images = product.images && Array.isArray(product.images) && product.images.length > 0
? product.images
: [imageSrc];
return {
id: product.id || String(Math.random()),
name: product.name || "Untitled Product",
description: product.description || "",
price: product.default_price?.unit_amount
? formatPrice(product.default_price.unit_amount, product.default_price.currency || "usd")
: product.price || "$0",
priceId: product.default_price?.id || product.priceId,
imageSrc,
imageAlt,
images,
brand: product.metadata?.brand || product.brand || "",
variant: product.metadata?.variant || product.variant || "",
rating: product.metadata?.rating ? parseFloat(product.metadata.rating) : undefined,
reviewCount: product.metadata?.reviewCount || undefined,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
};
});
} catch (error) {
return [];
}
} }
export async function fetchProduct(productId: string): Promise<Product | null> {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
if (!apiUrl || !projectId) {
return null;
}
try {
const url = `${apiUrl}/stripe/project/products/${productId}?projectId=${projectId}&expandDefaultPrice=true`;
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
return null;
}
const resp = await response.json();
const product = resp.data?.data || resp.data || resp;
if (!product || typeof product !== 'object') {
return null;
}
const metadata: Record<string, string | number | undefined> = {};
if (product.metadata && typeof product.metadata === 'object') {
Object.keys(product.metadata).forEach(key => {
const value = product.metadata[key];
if (value !== null && value !== undefined && value !== '') {
const numValue = parseFloat(String(value));
metadata[key] = isNaN(numValue) ? String(value) : numValue;
}
});
}
let priceValue = product.price;
if (!priceValue && product.default_price?.unit_amount) {
priceValue = formatPrice(product.default_price.unit_amount, product.default_price.currency || "usd");
}
if (!priceValue) {
priceValue = "$0";
}
const imageSrc = product.images?.[0] || product.imageSrc || "https://webuild-dev.s3.eu-north-1.amazonaws.com/default/placeholder3.avif";
const imageAlt = product.imageAlt || product.name || "";
const images = product.images && Array.isArray(product.images) && product.images.length > 0
? product.images
: [imageSrc];
return {
id: product.id || String(Math.random()),
name: product.name || "Untitled Product",
description: product.description || "",
price: priceValue,
priceId: product.default_price?.id || product.priceId,
imageSrc,
imageAlt,
images,
brand: product.metadata?.brand || product.brand || "",
variant: product.metadata?.variant || product.variant || "",
rating: product.metadata?.rating ? parseFloat(String(product.metadata.rating)) : undefined,
reviewCount: product.metadata?.reviewCount || undefined,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
};
} catch (error) {
return null;
}
}

View File

@@ -0,0 +1,185 @@
// Workout and metrics persistence layer
interface WorkoutSession {
id: string;
type: 'cardio' | 'training' | 'nutrition';
date: string;
data: Record<string, any>;
createdAt: number;
}
interface UserMetrics {
totalWorkouts: number;
totalDistance: number;
totalCalories: number;
totalWeight: number;
consistency: number; // days in a row
lastUpdated: number;
}
const STORAGE_KEYS = {
WORKOUTS: 'fitflow_workouts',
METRICS: 'fitflow_metrics',
USER_PROFILE: 'fitflow_user_profile',
} as const;
export class WorkoutStorageService {
// Workout Session Management
static saveWorkoutSession(session: Omit<WorkoutSession, 'id' | 'createdAt'>): WorkoutSession {
try {
const sessions = this.getWorkoutSessions();
const newSession: WorkoutSession = {
id: `workout_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
...session,
createdAt: Date.now(),
};
sessions.push(newSession);
localStorage.setItem(STORAGE_KEYS.WORKOUTS, JSON.stringify(sessions));
return newSession;
} catch (error) {
console.error('Error saving workout session:', error);
throw error;
}
}
static getWorkoutSessions(): WorkoutSession[] {
try {
const data = localStorage.getItem(STORAGE_KEYS.WORKOUTS);
return data ? JSON.parse(data) : [];
} catch (error) {
console.error('Error retrieving workout sessions:', error);
return [];
}
}
static getWorkoutSessionsByType(type: WorkoutSession['type']): WorkoutSession[] {
const sessions = this.getWorkoutSessions();
return sessions.filter(session => session.type === type);
}
static getWorkoutSessionsByDate(date: string): WorkoutSession[] {
const sessions = this.getWorkoutSessions();
return sessions.filter(session => session.date === date);
}
static updateWorkoutSession(id: string, updates: Partial<WorkoutSession>): WorkoutSession | null {
try {
const sessions = this.getWorkoutSessions();
const index = sessions.findIndex(s => s.id === id);
if (index === -1) return null;
const updated = { ...sessions[index], ...updates, id: sessions[index].id, createdAt: sessions[index].createdAt };
sessions[index] = updated;
localStorage.setItem(STORAGE_KEYS.WORKOUTS, JSON.stringify(sessions));
return updated;
} catch (error) {
console.error('Error updating workout session:', error);
return null;
}
}
static deleteWorkoutSession(id: string): boolean {
try {
const sessions = this.getWorkoutSessions();
const filtered = sessions.filter(s => s.id !== id);
localStorage.setItem(STORAGE_KEYS.WORKOUTS, JSON.stringify(filtered));
return filtered.length < sessions.length;
} catch (error) {
console.error('Error deleting workout session:', error);
return false;
}
}
// Metrics Management
static saveMetrics(metrics: UserMetrics): void {
try {
localStorage.setItem(STORAGE_KEYS.METRICS, JSON.stringify(metrics));
} catch (error) {
console.error('Error saving metrics:', error);
}
}
static getMetrics(): UserMetrics {
try {
const data = localStorage.getItem(STORAGE_KEYS.METRICS);
if (!data) {
return {
totalWorkouts: 0,
totalDistance: 0,
totalCalories: 0,
totalWeight: 0,
consistency: 0,
lastUpdated: Date.now(),
};
}
return JSON.parse(data);
} catch (error) {
console.error('Error retrieving metrics:', error);
return {
totalWorkouts: 0,
totalDistance: 0,
totalCalories: 0,
totalWeight: 0,
consistency: 0,
lastUpdated: Date.now(),
};
}
}
static updateMetrics(updates: Partial<UserMetrics>): UserMetrics {
const current = this.getMetrics();
const updated: UserMetrics = { ...current, ...updates, lastUpdated: Date.now() };
this.saveMetrics(updated);
return updated;
}
// Calculated Metrics
static calculateMetricsFromSessions(): UserMetrics {
const sessions = this.getWorkoutSessions();
let totalDistance = 0;
let totalCalories = 0;
let totalWeight = 0;
sessions.forEach(session => {
if (session.data.distance) totalDistance += Number(session.data.distance) || 0;
if (session.data.calories) totalCalories += Number(session.data.calories) || 0;
if (session.data.weight) totalWeight += Number(session.data.weight) || 0;
});
return this.updateMetrics({
totalWorkouts: sessions.length,
totalDistance,
totalCalories,
totalWeight,
});
}
// Batch Operations
static clearAllData(): void {
try {
localStorage.removeItem(STORAGE_KEYS.WORKOUTS);
localStorage.removeItem(STORAGE_KEYS.METRICS);
localStorage.removeItem(STORAGE_KEYS.USER_PROFILE);
} catch (error) {
console.error('Error clearing data:', error);
}
}
static exportData(): { workouts: WorkoutSession[]; metrics: UserMetrics } {
return {
workouts: this.getWorkoutSessions(),
metrics: this.getMetrics(),
};
}
static importData(data: { workouts: WorkoutSession[]; metrics: UserMetrics }): void {
try {
localStorage.setItem(STORAGE_KEYS.WORKOUTS, JSON.stringify(data.workouts));
this.saveMetrics(data.metrics);
} catch (error) {
console.error('Error importing data:', error);
}
}
}
export type { WorkoutSession, UserMetrics };