Merge version_2 into main #5
@@ -1,118 +1,25 @@
|
||||
import { useEffect, useState, useRef, RefObject } from "react";
|
||||
'use client';
|
||||
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
const ANIMATION_SPEED = 0.05;
|
||||
const ROTATION_SPEED = 0.1;
|
||||
const MOUSE_MULTIPLIER = 0.5;
|
||||
const ROTATION_MULTIPLIER = 0.25;
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface UseDepth3DAnimationProps {
|
||||
itemRefs: RefObject<(HTMLElement | null)[]>;
|
||||
containerRef: RefObject<HTMLDivElement | null>;
|
||||
perspectiveRef?: RefObject<HTMLDivElement | null>;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
export const useDepth3DAnimation = (elementRef: React.RefObject<HTMLElement>) => {
|
||||
const [isActive, setIsActive] = useState(false);
|
||||
|
||||
export const useDepth3DAnimation = ({
|
||||
itemRefs,
|
||||
containerRef,
|
||||
perspectiveRef,
|
||||
isEnabled,
|
||||
}: UseDepth3DAnimationProps) => {
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
|
||||
// Detect mobile viewport
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
};
|
||||
if (!elementRef.current) return;
|
||||
|
||||
checkMobile();
|
||||
window.addEventListener("resize", checkMobile);
|
||||
const handleMouseEnter = () => setIsActive(true);
|
||||
const handleMouseLeave = () => setIsActive(false);
|
||||
|
||||
const element = elementRef.current;
|
||||
element.addEventListener('mouseenter', handleMouseEnter);
|
||||
element.addEventListener('mouseleave', handleMouseLeave);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", checkMobile);
|
||||
element.removeEventListener('mouseenter', handleMouseEnter);
|
||||
element.removeEventListener('mouseleave', handleMouseLeave);
|
||||
};
|
||||
}, []);
|
||||
}, [elementRef]);
|
||||
|
||||
// 3D mouse-tracking effect (desktop only)
|
||||
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 };
|
||||
return { isActive };
|
||||
};
|
||||
|
||||
@@ -1,149 +1,26 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import React, { Children, useCallback } from "react";
|
||||
import { cls } from "@/lib/utils";
|
||||
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";
|
||||
import React, { useRef } from 'react';
|
||||
import { CardStackItemShape } from '@/components/cardStack/types';
|
||||
|
||||
interface TimelineBaseProps {
|
||||
children: React.ReactNode;
|
||||
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;
|
||||
items: CardStackItemShape[];
|
||||
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 = ({
|
||||
children,
|
||||
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);
|
||||
}, []);
|
||||
const TimelineBase: React.FC<TimelineBaseProps> = ({ items, className = '' }) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<section
|
||||
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
|
||||
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 ref={containerRef} className={`timeline-container ${className}`}>
|
||||
{items.map((item, index) => (
|
||||
<div key={item.id || index} className="timeline-item">
|
||||
<div className="timeline-marker" />
|
||||
<div className="timeline-content">{item.title}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
TimelineBase.displayName = "TimelineBase";
|
||||
|
||||
export default React.memo(TimelineBase);
|
||||
export default TimelineBase;
|
||||
|
||||
@@ -1,131 +1,88 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import ContactForm from "@/components/form/ContactForm";
|
||||
import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds";
|
||||
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" }
|
||||
>;
|
||||
import React, { useState } from 'react';
|
||||
import EmailSignupForm from '@/components/form/EmailSignupForm';
|
||||
import TextAnimation from '@/components/text/TextAnimation';
|
||||
|
||||
interface ContactCenterProps {
|
||||
title: string;
|
||||
description: string;
|
||||
tag: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
background: ContactCenterBackgroundProps;
|
||||
useInvertedBackground: boolean;
|
||||
tagClassName?: string;
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
termsText?: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
formWrapperClassName?: string;
|
||||
formClassName?: string;
|
||||
inputClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
termsClassName?: string;
|
||||
tag: string;
|
||||
title: string;
|
||||
description: string;
|
||||
background: { variant: string };
|
||||
useInvertedBackground: boolean;
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
termsText?: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
tagClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
formWrapperClassName?: string;
|
||||
formClassName?: string;
|
||||
inputClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
termsClassName?: string;
|
||||
}
|
||||
|
||||
const ContactCenter = ({
|
||||
title,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
background,
|
||||
useInvertedBackground,
|
||||
tagClassName = "",
|
||||
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 = "",
|
||||
titleClassName = "",
|
||||
descriptionClassName = "",
|
||||
formWrapperClassName = "",
|
||||
formClassName = "",
|
||||
inputClassName = "",
|
||||
buttonClassName = "",
|
||||
buttonTextClassName = "",
|
||||
termsClassName = "",
|
||||
}: ContactCenterProps) => {
|
||||
const ContactCenter: React.FC<ContactCenterProps> = ({
|
||||
tag,
|
||||
title,
|
||||
description,
|
||||
background,
|
||||
useInvertedBackground,
|
||||
inputPlaceholder = 'Enter your email',
|
||||
buttonText = 'Sign Up',
|
||||
termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.", onSubmit,
|
||||
className = '',
|
||||
containerClassName = '',
|
||||
contentClassName = '',
|
||||
tagClassName = '',
|
||||
titleClassName = '',
|
||||
descriptionClassName = '',
|
||||
formWrapperClassName = '',
|
||||
formClassName = '',
|
||||
inputClassName = '',
|
||||
buttonClassName = '',
|
||||
buttonTextClassName = '',
|
||||
termsClassName = '',
|
||||
}) => {
|
||||
const [email, setEmail] = useState('');
|
||||
|
||||
const handleSubmit = async (email: string) => {
|
||||
try {
|
||||
await sendContactEmail({ email });
|
||||
console.log("Email send successfully");
|
||||
} catch (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
}
|
||||
};
|
||||
const handleSubmit = () => {
|
||||
if (onSubmit && email) {
|
||||
onSubmit(email);
|
||||
}
|
||||
};
|
||||
|
||||
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("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="relative z-10 w-full md:w-1/2">
|
||||
<ContactForm
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
title={title}
|
||||
description={description}
|
||||
useInvertedBackground={useInvertedBackground}
|
||||
inputPlaceholder={inputPlaceholder}
|
||||
buttonText={buttonText}
|
||||
termsText={termsText}
|
||||
onSubmit={handleSubmit}
|
||||
centered={true}
|
||||
tagClassName={tagClassName}
|
||||
titleClassName={titleClassName}
|
||||
descriptionClassName={descriptionClassName}
|
||||
formWrapperClassName={cls("md:w-8/10 2xl:w-6/10", formWrapperClassName)}
|
||||
formClassName={formClassName}
|
||||
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>
|
||||
</section>
|
||||
);
|
||||
return (
|
||||
<section className={`contact-center ${className}`}>
|
||||
<div className={`container ${containerClassName}`}>
|
||||
<div className={`content ${contentClassName}`}>
|
||||
{tag && <div className={`tag ${tagClassName}`}>{tag}</div>}
|
||||
<TextAnimation className={titleClassName}>{title}</TextAnimation>
|
||||
<p className={descriptionClassName}>{description}</p>
|
||||
<div className={`form-wrapper ${formWrapperClassName}`}>
|
||||
<EmailSignupForm
|
||||
value={email}
|
||||
onChange={setEmail}
|
||||
placeholder={inputPlaceholder}
|
||||
buttonText={buttonText}
|
||||
onSubmit={handleSubmit}
|
||||
formClassName={formClassName}
|
||||
inputClassName={inputClassName}
|
||||
buttonClassName={buttonClassName}
|
||||
buttonTextClassName={buttonTextClassName}
|
||||
/>
|
||||
</div>
|
||||
{termsText && <p className={`terms ${termsClassName}`}>{termsText}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
ContactCenter.displayName = "ContactCenter";
|
||||
|
||||
export default ContactCenter;
|
||||
|
||||
@@ -1,171 +1,51 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import ContactForm from "@/components/form/ContactForm";
|
||||
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" }
|
||||
>;
|
||||
import React, { useState } from 'react';
|
||||
import EmailSignupForm from '@/components/form/EmailSignupForm';
|
||||
|
||||
interface ContactSplitProps {
|
||||
title: string;
|
||||
description: string;
|
||||
tag: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
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;
|
||||
title: string;
|
||||
description: string;
|
||||
contactInfo: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const ContactSplit = ({
|
||||
title,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
background,
|
||||
useInvertedBackground,
|
||||
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 ContactSplit: React.FC<ContactSplitProps> = ({
|
||||
title,
|
||||
description,
|
||||
contactInfo,
|
||||
onSubmit,
|
||||
className = '',
|
||||
}) => {
|
||||
const [email, setEmail] = useState('');
|
||||
|
||||
const handleSubmit = async (email: string) => {
|
||||
try {
|
||||
await sendContactEmail({ email });
|
||||
console.log("Email send successfully");
|
||||
} catch (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
}
|
||||
};
|
||||
const handleEmailSubmit = () => {
|
||||
if (onSubmit && email) {
|
||||
onSubmit(email);
|
||||
}
|
||||
};
|
||||
|
||||
const contactContent = (
|
||||
<div className="relative card rounded-theme-capped p-6 py-15 md:py-6 flex items-center justify-center">
|
||||
<ContactForm
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
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>
|
||||
return (
|
||||
<section className={`contact-split ${className}`}>
|
||||
<div className="contact-split-container">
|
||||
<div className="contact-split-left">
|
||||
<h2>{title}</h2>
|
||||
<p>{description}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
const mediaContent = (
|
||||
<div ref={mediaContainerRef} className={cls("overflow-hidden rounded-theme-capped card h-130", mediaWrapperClassName)}>
|
||||
<MediaContent
|
||||
imageSrc={imageSrc}
|
||||
videoSrc={videoSrc}
|
||||
imageAlt={imageAlt}
|
||||
videoAriaLabel={videoAriaLabel}
|
||||
imageClassName={cls("relative z-1 w-full h-full object-cover", mediaClassName)}
|
||||
/>
|
||||
<div className="contact-split-right">
|
||||
<EmailSignupForm
|
||||
value={email}
|
||||
onChange={setEmail}
|
||||
placeholder="Enter your email"
|
||||
buttonText="Get Started"
|
||||
onSubmit={handleEmailSubmit}
|
||||
/>
|
||||
<p className="contact-info">{contactInfo}</p>
|
||||
</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 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>
|
||||
);
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
ContactSplit.displayName = "ContactSplit";
|
||||
|
||||
export default ContactSplit;
|
||||
|
||||
@@ -1,214 +1,42 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { 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;
|
||||
}
|
||||
import React, { useState } from 'react';
|
||||
import EmailSignupForm from '@/components/form/EmailSignupForm';
|
||||
|
||||
interface ContactSplitFormProps {
|
||||
title: string;
|
||||
description: string;
|
||||
inputs: InputField[];
|
||||
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;
|
||||
title: string;
|
||||
description: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const ContactSplitForm = ({
|
||||
title,
|
||||
description,
|
||||
inputs,
|
||||
textarea,
|
||||
useInvertedBackground,
|
||||
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 });
|
||||
const ContactSplitForm: React.FC<ContactSplitFormProps> = ({
|
||||
title,
|
||||
description,
|
||||
className = '',
|
||||
}) => {
|
||||
const [email, setEmail] = useState('');
|
||||
|
||||
// Validate minimum inputs requirement
|
||||
if (inputs.length < 2) {
|
||||
throw new Error("ContactSplitForm requires at least 2 inputs");
|
||||
const handleSubmit = () => {
|
||||
if (email) {
|
||||
console.log('Form submitted with email:', email);
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize form data dynamically
|
||||
const initialFormData: Record<string, string> = {};
|
||||
inputs.forEach(input => {
|
||||
initialFormData[input.name] = "";
|
||||
});
|
||||
if (textarea) {
|
||||
initialFormData[textarea.name] = "";
|
||||
}
|
||||
|
||||
const [formData, setFormData] = useState(initialFormData);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
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>
|
||||
);
|
||||
|
||||
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>
|
||||
);
|
||||
return (
|
||||
<section className={`contact-split-form ${className}`}>
|
||||
<div className="contact-form-container">
|
||||
<h2>{title}</h2>
|
||||
<p>{description}</p>
|
||||
<EmailSignupForm
|
||||
value={email}
|
||||
onChange={setEmail}
|
||||
placeholder="Enter your email"
|
||||
buttonText="Submit"
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
ContactSplitForm.displayName = "ContactSplitForm";
|
||||
|
||||
export default ContactSplitForm;
|
||||
|
||||
@@ -1,248 +1,37 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { memo } 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";
|
||||
import React from 'react';
|
||||
|
||||
type PricingPlan = {
|
||||
id: string;
|
||||
badge: string;
|
||||
badgeIcon?: LucideIcon;
|
||||
price: string;
|
||||
subtitle: string;
|
||||
buttons: ButtonConfig[];
|
||||
features: string[];
|
||||
};
|
||||
interface PricingCard {
|
||||
id: string;
|
||||
name: string;
|
||||
price: string;
|
||||
features: string[];
|
||||
}
|
||||
|
||||
interface PricingCardEightProps {
|
||||
plans: PricingPlan[];
|
||||
carouselMode?: "auto" | "buttons";
|
||||
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;
|
||||
cards: PricingCard[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface PricingCardItemProps {
|
||||
plan: PricingPlan;
|
||||
shouldUseLightText: boolean;
|
||||
cardClassName?: string;
|
||||
badgeClassName?: string;
|
||||
priceClassName?: string;
|
||||
subtitleClassName?: string;
|
||||
planButtonContainerClassName?: string;
|
||||
planButtonClassName?: string;
|
||||
featuresClassName?: string;
|
||||
featureItemClassName?: string;
|
||||
}
|
||||
|
||||
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}
|
||||
/>
|
||||
const PricingCardEight: React.FC<PricingCardEightProps> = ({ cards, className = '' }) => {
|
||||
return (
|
||||
<div className={`pricing-card-eight ${className}`}>
|
||||
{cards.map((card) => (
|
||||
<div key={card.id} className="pricing-card">
|
||||
<h3>{card.name}</h3>
|
||||
<div className="price-section">
|
||||
<span>{card.price}</span>
|
||||
</div>
|
||||
<ul className="features-list">
|
||||
{card.features.map((feature, index) => (
|
||||
<li key={index}>{feature}</li>
|
||||
))}
|
||||
</CardStack>
|
||||
);
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
PricingCardEight.displayName = "PricingCardEight";
|
||||
|
||||
export default PricingCardEight;
|
||||
|
||||
@@ -1,84 +1,29 @@
|
||||
'use client';
|
||||
|
||||
import { useWorkoutData } from '@/hooks/useWorkoutData';
|
||||
import { UserMetrics } from '@/lib/storage/workoutStorage';
|
||||
import React from 'react';
|
||||
|
||||
interface WorkoutMetricsDisplayProps {
|
||||
className?: string;
|
||||
showRefresh?: boolean;
|
||||
onRefresh?: () => void;
|
||||
interface MetricDisplay {
|
||||
label: string;
|
||||
value: string | number;
|
||||
}
|
||||
|
||||
export const WorkoutMetricsDisplay: React.FC<WorkoutMetricsDisplayProps> = ({
|
||||
interface WorkoutMetricsDisplayProps {
|
||||
metrics: MetricDisplay[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const WorkoutMetricsDisplay: React.FC<WorkoutMetricsDisplayProps> = ({
|
||||
metrics,
|
||||
className = '',
|
||||
showRefresh = true,
|
||||
onRefresh
|
||||
}) => {
|
||||
const { metrics, refreshMetrics, isLoading } = useWorkoutData();
|
||||
|
||||
const handleRefresh = () => {
|
||||
refreshMetrics();
|
||||
onRefresh?.();
|
||||
};
|
||||
|
||||
if (isLoading || !metrics) {
|
||||
return <div className={className}>Loading metrics...</div>;
|
||||
}
|
||||
|
||||
const formatMetric = (value: number, unit: string) => {
|
||||
return `${value.toLocaleString()}${unit}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`workout-metrics ${className}`}>
|
||||
<div className="metrics-grid">
|
||||
<div className="metric-card">
|
||||
<h3>Total Steps</h3>
|
||||
<p>{formatMetric(metrics.totalSteps, ' steps')}</p>
|
||||
<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 className="metric-card">
|
||||
<h3>Total Distance</h3>
|
||||
<p>{formatMetric(metrics.totalDistance, ' km')}</p>
|
||||
</div>
|
||||
<div className="metric-card">
|
||||
<h3>Total Calories</h3>
|
||||
<p>{formatMetric(metrics.totalCalories, ' kcal')}</p>
|
||||
</div>
|
||||
<div className="metric-card">
|
||||
<h3>Total Volume</h3>
|
||||
<p>{formatMetric(metrics.totalVolume, ' kg')}</p>
|
||||
</div>
|
||||
<div className="metric-card">
|
||||
<h3>Workout Streak</h3>
|
||||
<p>{metrics.workoutStreak} days</p>
|
||||
</div>
|
||||
{metrics.lastWorkoutDate && (
|
||||
<div className="metric-card">
|
||||
<h3>Last Workout</h3>
|
||||
<p>{new Date(metrics.lastWorkoutDate).toLocaleDateString()}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{Object.keys(metrics.personalRecords).length > 0 && (
|
||||
<div className="personal-records">
|
||||
<h3>Personal Records</h3>
|
||||
<ul>
|
||||
{Object.entries(metrics.personalRecords).map(([exercise, weight]) => (
|
||||
<li key={exercise}>
|
||||
<span>{exercise}</span>
|
||||
<span>{weight} kg</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showRefresh && (
|
||||
<button onClick={handleRefresh} className="refresh-button">
|
||||
Refresh Metrics
|
||||
</button>
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,117 +1,81 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import { Product } from "@/lib/api/product";
|
||||
import { useState } from 'react';
|
||||
|
||||
export type CheckoutItem = {
|
||||
productId: string;
|
||||
quantity: number;
|
||||
imageSrc?: string;
|
||||
imageAlt?: string;
|
||||
metadata?: {
|
||||
brand?: string;
|
||||
variant?: string;
|
||||
rating?: number;
|
||||
reviewCount?: string;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
interface CartItem {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CheckoutState {
|
||||
items: CartItem[];
|
||||
total: number;
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -1,115 +1,49 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } 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";
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export type SortOption = "Newest" | "Price: Low-High" | "Price: High-Low";
|
||||
|
||||
interface UseProductCatalogOptions {
|
||||
basePath?: string;
|
||||
interface CatalogProduct {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
export function useProductCatalog(options: UseProductCatalogOptions = {}) {
|
||||
const { basePath = "/shop" } = options;
|
||||
const router = useRouter();
|
||||
const { products: fetchedProducts, isLoading } = useProducts();
|
||||
interface UseProductCatalogState {
|
||||
products: CatalogProduct[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [category, setCategory] = useState("All");
|
||||
const [sort, setSort] = useState<SortOption>("Newest");
|
||||
export const useProductCatalog = () => {
|
||||
const [state, setState] = useState<UseProductCatalogState>({
|
||||
products: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const handleProductClick = useCallback((productId: string) => {
|
||||
router.push(`${basePath}/${productId}`);
|
||||
}, [router, basePath]);
|
||||
|
||||
const catalogProducts: CatalogProduct[] = useMemo(() => {
|
||||
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),
|
||||
useEffect(() => {
|
||||
// Simulate loading products
|
||||
const loadProducts = async () => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
try {
|
||||
// Mock data
|
||||
const mockProducts: CatalogProduct[] = [
|
||||
{ id: '1', name: 'Product 1', price: 99.99, category: 'Electronics' },
|
||||
{ id: '2', name: 'Product 2', price: 149.99, category: 'Sports' },
|
||||
];
|
||||
setState({ products: mockProducts, loading: false, error: null });
|
||||
} catch (err) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: 'Failed to load products',
|
||||
}));
|
||||
}, [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;
|
||||
};
|
||||
|
||||
@@ -1,196 +1,52 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } 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";
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
interface ProductImage {
|
||||
src: string;
|
||||
alt: string;
|
||||
interface ProductDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface ProductMeta {
|
||||
salePrice?: string;
|
||||
ribbon?: string;
|
||||
inventoryStatus?: string;
|
||||
inventoryQuantity?: number;
|
||||
sku?: string;
|
||||
interface UseProductDetailState {
|
||||
product: ProductDetail | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function useProductDetail(productId: string) {
|
||||
const { product, isLoading, error } = useProduct(productId);
|
||||
const [selectedQuantity, setSelectedQuantity] = useState(1);
|
||||
const [selectedVariants, setSelectedVariants] = useState<Record<string, string>>({});
|
||||
export const useProductDetail = (productId: string) => {
|
||||
const [state, setState] = useState<UseProductDetailState>({
|
||||
product: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const images = useMemo<ProductImage[]>(() => {
|
||||
if (!product) return [];
|
||||
useEffect(() => {
|
||||
if (!productId) return;
|
||||
|
||||
if (product.images && product.images.length > 0) {
|
||||
return product.images.map((src, index) => ({
|
||||
src,
|
||||
alt: product.imageAlt || `${product.name} - Image ${index + 1}`,
|
||||
}));
|
||||
}
|
||||
return [{
|
||||
src: product.imageSrc,
|
||||
alt: product.imageAlt || product.name,
|
||||
}];
|
||||
}, [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,
|
||||
const loadProduct = async () => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
try {
|
||||
// Mock data
|
||||
const mockProduct: ProductDetail = {
|
||||
id: productId,
|
||||
name: 'Sample Product',
|
||||
price: 99.99,
|
||||
description: 'This is a sample product',
|
||||
};
|
||||
}, [product]);
|
||||
|
||||
const variants = useMemo<ProductVariant[]>(() => {
|
||||
if (!product) return [];
|
||||
|
||||
const variantList: ProductVariant[] = [];
|
||||
|
||||
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,
|
||||
setState({ product: mockProduct, loading: false, error: null });
|
||||
} catch (err) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: 'Failed to load product',
|
||||
}));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
loadProduct();
|
||||
}, [productId]);
|
||||
|
||||
return state;
|
||||
};
|
||||
|
||||
@@ -1,219 +1,42 @@
|
||||
export type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
price: string;
|
||||
imageSrc: 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;
|
||||
'use client';
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export const fetchProductList = async (): Promise<ApiResponse<Product[]>> => {
|
||||
try {
|
||||
const response = await fetch('/api/products');
|
||||
if (!response.ok) {
|
||||
return { success: false, message: 'Failed to fetch products' };
|
||||
}
|
||||
const data = await response.json();
|
||||
return { success: true, data };
|
||||
} catch (err) {
|
||||
return { success: false, message: 'Failed to fetch products' };
|
||||
}
|
||||
};
|
||||
|
||||
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[]> {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
return [];
|
||||
export const fetchProductById = async (
|
||||
productId: string
|
||||
): Promise<ApiResponse<Product>> => {
|
||||
try {
|
||||
const response = await fetch(`/api/products/${productId}`);
|
||||
if (!response.ok) {
|
||||
return { success: false, message: 'Product not found' };
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
const data = await response.json();
|
||||
return { success: true, data };
|
||||
} catch (err) {
|
||||
return { success: false, message: 'Product not found' };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,285 +1,64 @@
|
||||
// User data persistence layer for workouts and metrics
|
||||
'use client';
|
||||
|
||||
export interface ExerciseLog {
|
||||
id: string;
|
||||
name: string;
|
||||
sets: number;
|
||||
reps: number;
|
||||
weight?: number;
|
||||
}
|
||||
|
||||
export interface WorkoutSession {
|
||||
id: string;
|
||||
date: string;
|
||||
type: 'cardio' | 'training' | 'nutrition';
|
||||
duration?: number;
|
||||
distance?: number;
|
||||
calories?: number;
|
||||
duration: number;
|
||||
pace?: string;
|
||||
calories?: number;
|
||||
steps?: number;
|
||||
exercises?: ExerciseLog[];
|
||||
meals?: MealLog[];
|
||||
meals?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
calories: number;
|
||||
protein: number;
|
||||
carbs: number;
|
||||
fats: number;
|
||||
timestamp: string;
|
||||
}>;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface ExerciseLog {
|
||||
id: string;
|
||||
name: string;
|
||||
muscleGroup: string;
|
||||
sets: SetLog[];
|
||||
totalVolume?: number;
|
||||
}
|
||||
const STORAGE_KEY = 'workout_sessions';
|
||||
|
||||
export interface SetLog {
|
||||
reps: number;
|
||||
weight: number;
|
||||
restTime?: number;
|
||||
}
|
||||
export const workoutStorage = {
|
||||
getSessions: (): WorkoutSession[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored ? JSON.parse(stored) : [];
|
||||
},
|
||||
|
||||
export interface MealLog {
|
||||
id: string;
|
||||
name: string;
|
||||
calories: number;
|
||||
protein: number;
|
||||
carbs: number;
|
||||
fats: number;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface UserMetrics {
|
||||
totalSteps: number;
|
||||
totalDistance: number;
|
||||
totalCalories: number;
|
||||
totalVolume: number;
|
||||
workoutStreak: number;
|
||||
lastWorkoutDate?: string;
|
||||
personalRecords: Record<string, number>;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'fitflow_workouts';
|
||||
const METRICS_KEY = 'fitflow_metrics';
|
||||
|
||||
// Workout Session Management
|
||||
export const saveWorkoutSession = (session: WorkoutSession): boolean => {
|
||||
try {
|
||||
const existing = getWorkoutSessions();
|
||||
const updated = [...existing, { ...session, id: session.id || Date.now().toString() }];
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error saving workout session:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const getWorkoutSessions = (): WorkoutSession[] => {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEY);
|
||||
return data ? JSON.parse(data) : [];
|
||||
} catch (error) {
|
||||
console.error('Error retrieving workout sessions:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getWorkoutById = (id: string): WorkoutSession | null => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
return sessions.find(s => s.id === id) || null;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving workout by id:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateWorkoutSession = (id: string, updates: Partial<WorkoutSession>): boolean => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
const index = sessions.findIndex(s => s.id === id);
|
||||
if (index === -1) return false;
|
||||
sessions[index] = { ...sessions[index], ...updates, id };
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(sessions));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error updating workout session:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteWorkoutSession = (id: string): boolean => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
const filtered = sessions.filter(s => s.id !== id);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error deleting workout session:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const getWorkoutsByType = (type: 'cardio' | 'training' | 'nutrition'): WorkoutSession[] => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
return sessions.filter(s => s.type === type);
|
||||
} catch (error) {
|
||||
console.error('Error filtering workouts by type:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getWorkoutsByDateRange = (startDate: string, endDate: string): WorkoutSession[] => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
return sessions.filter(s => {
|
||||
const sessionDate = new Date(s.date);
|
||||
return sessionDate >= new Date(startDate) && sessionDate <= new Date(endDate);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error filtering workouts by date range:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Metrics Management
|
||||
export const saveUserMetrics = (metrics: UserMetrics): boolean => {
|
||||
try {
|
||||
localStorage.setItem(METRICS_KEY, JSON.stringify(metrics));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error saving user metrics:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const getUserMetrics = (): UserMetrics => {
|
||||
try {
|
||||
const data = localStorage.getItem(METRICS_KEY);
|
||||
return data ? JSON.parse(data) : getDefaultMetrics();
|
||||
} catch (error) {
|
||||
console.error('Error retrieving user metrics:', error);
|
||||
return getDefaultMetrics();
|
||||
}
|
||||
};
|
||||
|
||||
export const updateUserMetrics = (updates: Partial<UserMetrics>): boolean => {
|
||||
try {
|
||||
const current = getUserMetrics();
|
||||
const updated = { ...current, ...updates };
|
||||
return saveUserMetrics(updated);
|
||||
} catch (error) {
|
||||
console.error('Error updating user metrics:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const calculateMetricsFromSessions = (): UserMetrics => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
let totalSteps = 0;
|
||||
let totalDistance = 0;
|
||||
let totalCalories = 0;
|
||||
let totalVolume = 0;
|
||||
const personalRecords: Record<string, number> = {};
|
||||
|
||||
sessions.forEach(session => {
|
||||
if (session.steps) totalSteps += session.steps;
|
||||
if (session.distance) totalDistance += session.distance;
|
||||
if (session.calories) totalCalories += session.calories;
|
||||
if (session.exercises) {
|
||||
session.exercises.forEach(ex => {
|
||||
ex.sets.forEach(set => {
|
||||
totalVolume += set.weight * set.reps;
|
||||
const key = ex.name;
|
||||
if (!personalRecords[key] || set.weight > personalRecords[key]) {
|
||||
personalRecords[key] = set.weight;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const metrics: UserMetrics = {
|
||||
totalSteps,
|
||||
totalDistance,
|
||||
totalCalories,
|
||||
totalVolume,
|
||||
workoutStreak: calculateWorkoutStreak(sessions),
|
||||
lastWorkoutDate: sessions.length > 0 ? sessions[sessions.length - 1].date : undefined,
|
||||
personalRecords
|
||||
addSession: (session: Omit<WorkoutSession, 'id'>): WorkoutSession => {
|
||||
const sessions = workoutStorage.getSessions();
|
||||
const newSession: WorkoutSession = {
|
||||
...session,
|
||||
id: `session-${Date.now()}`,
|
||||
};
|
||||
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
console.error('Error calculating metrics:', error);
|
||||
return getDefaultMetrics();
|
||||
}
|
||||
};
|
||||
|
||||
export const calculateWorkoutStreak = (sessions: WorkoutSession[]): number => {
|
||||
if (sessions.length === 0) return 0;
|
||||
|
||||
const sortedSessions = [...sessions].sort((a, b) =>
|
||||
new Date(b.date).getTime() - new Date(a.date).getTime()
|
||||
);
|
||||
|
||||
let streak = 0;
|
||||
let currentDate = new Date();
|
||||
currentDate.setHours(0, 0, 0, 0);
|
||||
|
||||
for (const session of sortedSessions) {
|
||||
const sessionDate = new Date(session.date);
|
||||
sessionDate.setHours(0, 0, 0, 0);
|
||||
|
||||
const dayDiff = Math.floor((currentDate.getTime() - sessionDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (dayDiff === streak) {
|
||||
streak++;
|
||||
} else {
|
||||
break;
|
||||
sessions.push(newSession);
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(sessions));
|
||||
}
|
||||
}
|
||||
return newSession;
|
||||
},
|
||||
|
||||
return streak;
|
||||
};
|
||||
|
||||
const getDefaultMetrics = (): UserMetrics => ({
|
||||
totalSteps: 0,
|
||||
totalDistance: 0,
|
||||
totalCalories: 0,
|
||||
totalVolume: 0,
|
||||
workoutStreak: 0,
|
||||
personalRecords: {}
|
||||
});
|
||||
|
||||
// Bulk operations
|
||||
export const exportWorkoutData = (): string => {
|
||||
try {
|
||||
const sessions = getWorkoutSessions();
|
||||
const metrics = getUserMetrics();
|
||||
const data = { sessions, metrics, exportDate: new Date().toISOString() };
|
||||
return JSON.stringify(data, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error exporting data:', error);
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
export const importWorkoutData = (jsonData: string): boolean => {
|
||||
try {
|
||||
const data = JSON.parse(jsonData);
|
||||
if (data.sessions) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data.sessions));
|
||||
}
|
||||
if (data.metrics) {
|
||||
localStorage.setItem(METRICS_KEY, JSON.stringify(data.metrics));
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error importing data:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const clearAllData = (): boolean => {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
localStorage.removeItem(METRICS_KEY);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error clearing data:', error);
|
||||
return false;
|
||||
}
|
||||
getSessionsByDate: (date: string): WorkoutSession[] => {
|
||||
const sessions = workoutStorage.getSessions();
|
||||
return sessions.filter((s) => s.date.startsWith(date));
|
||||
},
|
||||
|
||||
getTodaysSessions: (): WorkoutSession[] => {
|
||||
const currentDate = new Date().toISOString().split('T')[0];
|
||||
return workoutStorage.getSessionsByDate(currentDate);
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user