32 Commits

Author SHA1 Message Date
f9ce33a09c Update src/app/page.tsx 2026-03-03 05:17:26 +00:00
2b8f870085 Update src/app/page.tsx 2026-03-03 05:13:50 +00:00
5f9f5136b3 Update src/app/layout.tsx 2026-03-03 05:13:49 +00:00
f7dfab92f6 Update src/app/page.tsx 2026-03-03 05:08:05 +00:00
a1e480e9c2 Update src/app/layout.tsx 2026-03-03 05:08:05 +00:00
5cd239b70f Update src/hooks/useProduct.ts 2026-03-03 05:00:31 +00:00
61054f6dea Update src/components/sections/product/ProductCardTwo.tsx 2026-03-03 05:00:31 +00:00
a47871032d Update src/components/sections/product/ProductCardThree.tsx 2026-03-03 05:00:31 +00:00
637bfd8222 Update src/components/sections/product/ProductCardOne.tsx 2026-03-03 05:00:30 +00:00
d28296e0ab Update src/components/sections/product/ProductCardFour.tsx 2026-03-03 05:00:30 +00:00
7905425b1a Update src/components/sections/contact/ContactSplit.tsx 2026-03-03 05:00:29 +00:00
876d805d49 Update src/components/ecommerce/productCatalog/ProductCatalog.tsx 2026-03-03 05:00:29 +00:00
b38d9f4158 Add src/components/cardStack/layouts/types.ts 2026-03-03 05:00:28 +00:00
e3d61b2f11 Update src/components/cardStack/layouts/timelines/TimelineBase.tsx 2026-03-03 05:00:28 +00:00
1150953185 Update src/components/cardStack/hooks/useCardAnimation.ts 2026-03-03 05:00:27 +00:00
36c32f58bd Update src/components/cardStack/CardStack.tsx 2026-03-03 05:00:27 +00:00
cd2b24ac04 Update src/app/page.tsx 2026-03-03 04:57:30 +00:00
e747e323aa Update src/app/layout.tsx 2026-03-03 04:57:29 +00:00
dc1aa5c51d Switch to version 3: modified src/lib/api/product.ts 2026-03-03 04:55:00 +00:00
6d0384a4bb Switch to version 3: modified src/hooks/useProductDetail.ts 2026-03-03 04:55:00 +00:00
0a56d74b86 Switch to version 3: modified src/hooks/useProductCatalog.ts 2026-03-03 04:54:59 +00:00
79ee098180 Switch to version 3: modified src/hooks/useCheckout.ts 2026-03-03 04:54:59 +00:00
819cf506ff Switch to version 3: modified src/components/sections/pricing/PricingCardEight.tsx 2026-03-03 04:54:58 +00:00
0a8a6c2ad1 Switch to version 3: modified src/components/sections/contact/ContactSplitForm.tsx 2026-03-03 04:54:58 +00:00
3f7d960cd2 Switch to version 3: modified src/components/sections/contact/ContactSplit.tsx 2026-03-03 04:54:57 +00:00
968d02da4d Switch to version 3: modified src/components/sections/contact/ContactCenter.tsx 2026-03-03 04:54:57 +00:00
810a5cfe4d Switch to version 3: modified src/components/cardStack/layouts/timelines/TimelineBase.tsx 2026-03-03 04:54:56 +00:00
83afb6e942 Switch to version 3: modified src/components/cardStack/hooks/useDepth3DAnimation.ts 2026-03-03 04:54:55 +00:00
d499bf276d Switch to version 3: modified src/app/page.tsx 2026-03-03 04:54:55 +00:00
359e805e27 Switch to version 3: modified src/app/layout.tsx 2026-03-03 04:54:54 +00:00
e81fc475da Merge version_4 into main
Merge version_4 into main
2026-03-03 04:48:28 +00:00
8796ab757a Merge version_4 into main
Merge version_4 into main
2026-03-03 04:46:12 +00:00
21 changed files with 2070 additions and 2111 deletions

View File

@@ -39,8 +39,8 @@ export default function RootLayout({
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<head> <head>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
</head> </head>
<ServiceWrapper> <ServiceWrapper>
<body className={`${inter.variable} antialiased`}> <body className={`${inter.variable} antialiased`}>
@@ -1417,4 +1417,4 @@ export default function RootLayout({
</ServiceWrapper> </ServiceWrapper>
</html> </html>
); );
} }

View File

@@ -5,13 +5,13 @@ import { useState, useEffect } from "react";
import NavbarStyleApple from "@/components/navbar/NavbarStyleApple/NavbarStyleApple"; import NavbarStyleApple from "@/components/navbar/NavbarStyleApple/NavbarStyleApple";
import HeroCentered from "@/components/sections/hero/HeroCentered"; import HeroCentered from "@/components/sections/hero/HeroCentered";
import MetricSplitMediaAbout from "@/components/sections/about/MetricSplitMediaAbout"; import MetricSplitMediaAbout from "@/components/sections/about/MetricSplitMediaAbout";
import FeatureCardSixteen from "@/components/sections/feature/FeatureCardSixteen"; import { FeatureCardSixteen } from "@/components/sections/feature/FeatureCardSixteen";
import MetricCardSeven from "@/components/sections/metrics/MetricCardSeven"; import { MetricCardSeven } from "@/components/sections/metrics/MetricCardSeven";
import TestimonialCardThirteen from "@/components/sections/testimonial/TestimonialCardThirteen"; import { TestimonialCardThirteen } from "@/components/sections/testimonial/TestimonialCardThirteen";
import FaqBase from "@/components/sections/faq/FaqBase"; import FaqBase from "@/components/sections/faq/FaqBase";
import ContactSplit from "@/components/sections/contact/ContactSplit"; import ContactSplit from "@/components/sections/contact/ContactSplit";
import FooterLogoEmphasis from "@/components/sections/footer/FooterLogoEmphasis"; import FooterLogoEmphasis from "@/components/sections/footer/FooterLogoEmphasis";
import TimelineProcessFlow from "@/components/cardStack/layouts/timelines/TimelineProcessFlow"; import { TimelineProcessFlow } from "@/components/cardStack/layouts/timelines/TimelineProcessFlow";
import { Moon, Sun } from "lucide-react"; import { Moon, Sun } from "lucide-react";
import gsap from "gsap"; import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger"; import ScrollTrigger from "gsap/ScrollTrigger";
@@ -39,104 +39,141 @@ export default function LandingPage() {
}; };
useEffect(() => { useEffect(() => {
// Apply initial theme
Object.entries(theme).forEach(([key, value]) => {
document.documentElement.style.setProperty(key, value);
});
// Initialize GSAP animations // Initialize GSAP animations
gsap.utils.toArray<HTMLElement>("[data-section]").forEach((section) => { const initGsapAnimations = () => {
// Fade in on scroll // Stagger animation for section elements
gsap.from(section, { const sections = document.querySelectorAll('[data-section]');
opacity: 0, sections.forEach((section) => {
duration: 0.8, const elements = section.querySelectorAll('h1, h2, h3, p, button, [data-animate]');
scrollTrigger: { elements.forEach((el, index) => {
trigger: section, gsap.set(el, { opacity: 0, y: 20 });
start: "top 80%", end: "top 20%", scrub: 1, ScrollTrigger.create({
markers: false trigger: el,
onEnter: () => {
gsap.to(el, {
opacity: 1,
y: 0,
duration: 0.6,
delay: index * 0.05,
ease: "power3.out"
});
},
once: true
});
});
});
// Hero section parallax
const hero = document.querySelector('#hero');
if (hero) {
const heroContent = hero.querySelector('[data-animate]');
if (heroContent) {
gsap.to(heroContent, {
scrollTrigger: {
trigger: hero,
start: "top center", end: "bottom center", scrub: 1
},
y: -50,
opacity: 0.8
});
} }
});
// Parallax effect on hero
if (section.id === "hero") {
gsap.to(section, {
y: 50,
duration: 0.5,
scrollTrigger: {
trigger: section,
start: "top center", end: "bottom center", scrub: 0.5,
markers: false
}
});
} }
});
// Animate hero title and description with stagger // Card scale animation on scroll
gsap.from("#hero h1, #hero p", { const cards = document.querySelectorAll('[class*="card"], [class*="Card"]');
opacity: 0, cards.forEach((card) => {
y: 30, gsap.set(card, { scale: 0.95, opacity: 0 });
duration: 0.8, ScrollTrigger.create({
stagger: 0.2, trigger: card,
delay: 0.3 onEnter: () => {
}); gsap.to(card, {
scale: 1,
// Button hover effects opacity: 1,
const buttons = document.querySelectorAll("button[class*='button']"); duration: 0.8,
buttons.forEach((button) => { ease: "back.out"
button.addEventListener("mouseenter", () => { });
gsap.to(button, { },
scale: 1.05, once: true
duration: 0.3,
overwrite: "auto"
}); });
}); });
button.addEventListener("mouseleave", () => {
gsap.to(button, { // Floating animation for images
scale: 1, const images = document.querySelectorAll('img[data-animate], [class*="image"] img');
duration: 0.3, images.forEach((img) => {
overwrite: "auto" gsap.to(img, {
y: -10,
duration: 3,
repeat: -1,
yoyo: true,
ease: "sine.inOut"
}); });
}); });
});
// Animate metric cards with scroll trigger // Text reveal animation
gsap.from("[class*='metric']", { const textElements = document.querySelectorAll('h1, h2, h3');
opacity: 0, textElements.forEach((text) => {
scale: 0.8, ScrollTrigger.create({
duration: 0.6, trigger: text,
stagger: 0.1, onEnter: () => {
scrollTrigger: { gsap.to(text, {
trigger: "#metrics", start: "top 80%", end: "top 20%", scrub: 1, backgroundPosition: "200% center", duration: 1.5,
markers: false ease: "power2.out"
} });
}); },
once: true
// Animate testimonial cards });
gsap.from("[class*='testimonial']", {
opacity: 0,
x: -30,
duration: 0.6,
stagger: 0.15,
scrollTrigger: {
trigger: "#testimonials", start: "top 80%", end: "top 20%", scrub: 0.5,
markers: false
}
});
// Text reveal effect on section titles
gsap.utils.toArray<HTMLElement>("[data-section] h2, [data-section] h3").forEach((heading) => {
gsap.from(heading, {
opacity: 0,
y: 20,
duration: 0.6,
scrollTrigger: {
trigger: heading,
start: "top 90%", end: "top 70%", scrub: 0.3,
markers: false
}
}); });
});
// Cleanup // Button hover glow effect
return () => { const buttons = document.querySelectorAll('button');
ScrollTrigger.getAll().forEach((trigger) => trigger.kill()); buttons.forEach((btn) => {
btn.addEventListener('mouseenter', () => {
gsap.to(btn, {
boxShadow: "0 0 20px rgba(0, 0, 0, 0.3)", duration: 0.3
});
});
btn.addEventListener('mouseleave', () => {
gsap.to(btn, {
boxShadow: "0 0 0px rgba(0, 0, 0, 0)", duration: 0.3
});
});
});
// Scroll-triggered counter animations
const counters = document.querySelectorAll('[data-count]');
counters.forEach((counter) => {
ScrollTrigger.create({
trigger: counter,
onEnter: () => {
const target = parseInt(counter.getAttribute('data-count')) || 0;
gsap.to(counter, {
textContent: target,
duration: 2,
snap: { textContent: 1 },
ease: "power2.out"
});
},
once: true
});
});
}; };
}, []);
// Wait for DOM to be fully loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initGsapAnimations);
} else {
initGsapAnimations();
}
return () => {
ScrollTrigger.getAll().forEach(trigger => trigger.kill());
};
}, [isDarkMode]);
return ( return (
<ThemeProvider <ThemeProvider
@@ -615,4 +652,4 @@ export default function LandingPage() {
</div> </div>
</ThemeProvider> </ThemeProvider>
); );
} }

View File

@@ -1,229 +1,50 @@
"use client"; "use client";
import { memo, Children } from "react"; import React, { useEffect, useRef, useState } from "react";
import { CardStackProps } from "./types"; import { useCardAnimation } from "./hooks/useCardAnimation";
import GridLayout from "./layouts/grid/GridLayout";
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 = ({ export interface CardStackItem {
children, id: string;
mode = "buttons", content: React.ReactNode;
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 export interface CardStackProps {
const gridConfig = gridConfigs[gridVariant]?.[itemCount]; items: CardStackItem[];
const hasFixedGridRows = gridConfig && 'gridRows' in gridConfig && gridConfig.gridRows; animationType?: "opacity" | "none" | "slide-up" | "blur-reveal";
className?: string;
containerClassName?: string;
cardClassName?: string;
ariaLabel?: string;
}
// If grid has fixed row heights and we have uniformGridCustomHeightClasses, const CardStack = React.forwardRef<HTMLDivElement, CardStackProps>(
// we need to use min-h-0 on md+ to prevent conflicts (
let adjustedHeightClasses = uniformGridCustomHeightClasses; {
if (hasFixedGridRows && uniformGridCustomHeightClasses) { items,
// Extract the mobile min-height and add md:min-h-0 animationType = "opacity", className = "", containerClassName = "", cardClassName = "", ariaLabel = "Card stack"},
const mobileMinHeight = uniformGridCustomHeightClasses.split(' ')[0]; ref
adjustedHeightClasses = `${mobileMinHeight} md:min-h-0`; ) => {
} const internalRef = useRef<HTMLDivElement>(null);
const resolvedRef = ref || internalRef;
// 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 ( return (
<ButtonCarousel <div
uniformGridCustomHeightClasses={adjustedHeightClasses} ref={resolvedRef}
animationType={carouselAnimationType} className={`relative w-full ${className}`}
title={title} aria-label={ariaLabel}
titleSegments={titleSegments} >
description={description} <div className={`relative ${containerClassName}`}>
tag={tag} {items.map((item) => (
tagIcon={tagIcon} <div key={item.id} className={`relative ${cardClassName}`}>
tagAnimation={tagAnimation} {item.content}
buttons={buttons} </div>
buttonAnimation={buttonAnimation} ))}
textboxLayout={textboxLayout} </div>
useInvertedBackground={useInvertedBackground} </div>
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"; CardStack.displayName = "CardStack";
export default memo(CardStack); export default CardStack;

View File

@@ -1,187 +1,35 @@
import { useRef } from "react"; import { useEffect, useRef } from "react";
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); export interface UseCardAnimationOptions {
animationType?: "opacity" | "none" | "slide-up" | "blur-reveal";
interface UseCardAnimationProps { staggerDelay?: number;
animationType: CardAnimationType | "depth-3d"; duration?: number;
itemCount: number;
isGrid?: boolean;
supports3DAnimation?: boolean;
gridVariant?: GridVariant;
useIndividualTriggers?: boolean;
} }
export const useCardAnimation = ({ export const useCardAnimation = (options: UseCardAnimationOptions = {}) => {
animationType, const { animationType = "opacity", staggerDelay = 0.1, duration = 0.6 } =
itemCount, options;
isGrid = true, const containerRef = useRef<HTMLDivElement>(null);
supports3DAnimation = false,
gridVariant,
useIndividualTriggers = false
}: 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 useEffect(() => {
const { isMobile } = useDepth3DAnimation({ if (!containerRef.current || animationType === "none") return;
itemRefs,
const cards = containerRef.current.querySelectorAll("[data-card]");
if (cards.length === 0) return;
cards.forEach((card, index) => {
const element = card as HTMLElement;
element.style.opacity = "0";
const delay = index * staggerDelay;
setTimeout(() => {
element.style.transition = `opacity ${duration}s ease-in-out`;
element.style.opacity = "1";
}, delay * 1000);
});
}, [animationType, staggerDelay, duration]);
return {
containerRef, containerRef,
perspectiveRef, };
isEnabled: animationType === "depth-3d" && isGrid && supports3DAnimation && gridVariant === "uniform-all-items-equal",
});
// 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,27 +1,118 @@
import { useEffect } from "react"; import { useEffect, useState, useRef, RefObject } from "react";
import gsap from "gsap";
export const useDepth3DAnimation = (containerRef: React.RefObject<HTMLDivElement>) => { const MOBILE_BREAKPOINT = 768;
const ANIMATION_SPEED = 0.05;
const ROTATION_SPEED = 0.1;
const MOUSE_MULTIPLIER = 0.5;
const ROTATION_MULTIPLIER = 0.25;
interface UseDepth3DAnimationProps {
itemRefs: RefObject<(HTMLElement | null)[]>;
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(() => {
if (!containerRef.current) return; const checkMobile = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
const container = containerRef.current; checkMobile();
const cards = container.querySelectorAll("[data-card]"); window.addEventListener("resize", checkMobile);
// Add scroll-triggered 3D animations return () => {
cards.forEach((card, index) => { window.removeEventListener("resize", checkMobile);
gsap.from(card, { };
opacity: 0, }, []);
y: 50,
rotationX: 10, // 3D mouse-tracking effect (desktop only)
duration: 0.8, useEffect(() => {
delay: index * 0.1, if (!isEnabled || isMobile) return;
scrollTrigger: {
trigger: card, let animationFrameId: number;
start: "top 80%", end: "top 20%", scrub: 1, let isAnimating = true;
markers: false
} // 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)`;
}); });
});
}, [containerRef]); 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,44 +1,44 @@
import React, { useMemo } from "react"; import React from "react";
import { CardStack, CardStackProps } from "@/components/cardStack"; import { TimelineItem } from "../types";
import { cn } from "@/lib/utils";
export interface TimelineItem { export interface TimelineBaseProps {
id: string;
reverse?: boolean;
media?: React.ReactNode;
content?: React.ReactNode;
}
export interface TimelineBaseProps extends Omit<CardStackProps, "items"> {
items: TimelineItem[]; items: TimelineItem[];
animationType?: "slide-up" | "none" | "opacity" | "blur-reveal"; title?: string;
description?: string;
tag?: string;
animationType?: string;
textboxLayout?: string;
className?: string;
containerClassName?: string;
children?: React.ReactNode;
} }
export const TimelineBase: React.FC<TimelineBaseProps> = ({ const TimelineBase = React.forwardRef<HTMLDivElement, TimelineBaseProps>(
items, (
animationType = "slide-up", className, {
containerClassName, items,
...props title,
}) => { description,
const timelineItems = useMemo( tag,
() => animationType = "none", textboxLayout = "default", className = "", containerClassName = "", children,
items.map((item) => ({ },
id: item.id, ref
title: "", description: "", content: item.content, ) => {
media: item.media, return (
reverse: item.reverse <div ref={ref} className={`w-full ${className}`}>
})), {tag && <div className="text-sm font-medium mb-2">{tag}</div>}
[items] {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
); {description && (
<p className="text-base text-foreground/75 mb-8">{description}</p>
)}
<div className={`relative ${containerClassName}`}>
{children}
</div>
</div>
);
}
);
return ( TimelineBase.displayName = "TimelineBase";
<CardStack
items={timelineItems}
className={cn("timeline-base", className)}
containerClassName={containerClassName}
{...props}
/>
);
};
export default TimelineBase; export default TimelineBase;

View File

@@ -0,0 +1,4 @@
export interface TimelineItem {
id: string;
[key: string]: any;
}

View File

@@ -1,156 +1,79 @@
"use client"; "use client";
import { memo, useMemo, useCallback } from "react"; import React from "react";
import { useRouter } from "next/navigation";
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 ProductCatalogItem from "./ProductCatalogItem";
import type { CatalogProduct } from "./ProductCatalogItem";
interface ProductCatalogProps { export interface CatalogProduct {
layout: "page" | "section"; id: string;
products?: CatalogProduct[]; name: string;
searchValue?: string; price: string;
onSearchChange?: (value: string) => void; imageSrc: string;
searchPlaceholder?: string; imageAlt?: string;
filters?: ProductVariant[]; category?: string;
emptyMessage?: string; rating?: number;
className?: string; reviewCount?: string;
gridClassName?: string; onProductClick?: () => void;
cardClassName?: string; onFavorite?: () => void;
imageClassName?: string; isFavorited?: boolean;
searchClassName?: string;
filterClassName?: string;
toolbarClassName?: string;
} }
const ProductCatalog = ({ export interface ProductCatalogProps {
layout, products: CatalogProduct[];
products: productsProp, title?: string;
searchValue = "", description?: string;
onSearchChange, className?: string;
searchPlaceholder = "Search products...", containerClassName?: string;
filters, gridClassName?: string;
emptyMessage = "No products found", cardClassName?: string;
className = "", onProductClick?: (product: CatalogProduct) => void;
gridClassName = "", ariaLabel?: string;
cardClassName = "", }
imageClassName = "",
searchClassName = "",
filterClassName = "",
toolbarClassName = "",
}: ProductCatalogProps) => {
const router = useRouter();
const { products: fetchedProducts, isLoading } = useProducts();
const handleProductClick = useCallback((productId: string) => { const ProductCatalog = React.forwardRef<HTMLDivElement, ProductCatalogProps>(
router.push(`/shop/${productId}`); (
}, [router]); {
products,
const products: CatalogProduct[] = useMemo(() => { title,
if (productsProp && productsProp.length > 0) { description,
return productsProp; className = "", containerClassName = "", gridClassName = "", cardClassName = "", onProductClick,
} ariaLabel = "Product catalog"},
ref
if (fetchedProducts.length === 0) { ) => {
return []; const normalizedProducts = Array.isArray(products)
} ? products.map((p) => ({
...p,
return fetchedProducts.map((product) => ({ price: typeof p.price === "number" ? p.price.toString() : p.price,
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 ( return (
<section <div
className={cls( ref={ref}
"relative w-content-width mx-auto", className={`w-full ${className}`}
layout === "page" ? "pt-hero-page-padding pb-20" : "py-20", aria-label={ariaLabel}
className >
)} {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
> {description && (
{(onSearchChange || (filters && filters.length > 0)) && ( <p className="text-base text-foreground/75 mb-8">{description}</p>
<div )}
className={cls( <div className={`grid grid-cols-1 gap-6 ${gridClassName}`}>
"flex flex-col md:flex-row gap-4 md:items-end mb-6", {normalizedProducts.map((product) => (
toolbarClassName <ProductCatalogItem
)} key={product.id}
> product={product}
{onSearchChange && ( className={cardClassName}
<Input onProductClick={() => {
value={searchValue} product.onProductClick?.();
onChange={onSearchChange} onProductClick?.(product);
placeholder={searchPlaceholder} }}
ariaLabel={searchPlaceholder} />
className={cls("flex-1 w-full h-9 text-sm", searchClassName)} ))}
/> </div>
)} </div>
{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"; ProductCatalog.displayName = "ProductCatalog";
export default memo(ProductCatalog); export default ProductCatalog;

View File

@@ -1,64 +1,131 @@
import React, { useState } from "react"; "use client";
import { cn } from "@/lib/utils";
export interface ContactCenterProps { import ContactForm from "@/components/form/ContactForm";
tag?: string; import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds";
title: string; import { cls } from "@/lib/utils";
description?: string; import { LucideIcon } from "lucide-react";
contactEmail?: string; import { sendContactEmail } from "@/utils/sendContactEmail";
contactPhone?: string; import type { ButtonAnimationType } from "@/types/button";
useInvertedBackground?: boolean;
className?: string; type ContactCenterBackgroundProps = Extract<
containerClassName?: string; 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 {
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;
} }
export const ContactCenter: React.FC<ContactCenterProps> = ({ const ContactCenter = ({
tag, title,
title, description,
description, tag,
contactEmail, tagIcon,
contactPhone, tagAnimation,
useInvertedBackground = false, background,
className, useInvertedBackground,
containerClassName tagClassName = "",
}) => { inputPlaceholder = "Enter your email",
const [email, setEmail] = useState(""); 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 handleSubmit = (e: React.FormEvent) => { const handleSubmit = async (email: string) => {
e.preventDefault(); try {
setEmail(""); await sendContactEmail({ email });
}; console.log("Email send successfully");
} catch (error) {
console.error("Failed to send email:", error);
}
};
return ( return (
<div <section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
className={cn( <div className={cls("w-content-width mx-auto relative z-10", containerClassName)}>
"w-full py-20 px-4", useInvertedBackground && "bg-accent/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
<div className={cn("max-w-2xl mx-auto text-center", className)}> tag={tag}
{tag && <p className="text-sm font-semibold mb-2 text-accent">{tag}</p>} tagIcon={tagIcon}
<h2 className="text-4xl font-bold mb-4">{title}</h2> tagAnimation={tagAnimation}
{description && <p className="text-lg text-muted-foreground mb-8">{description}</p>} title={title}
description={description}
<form onSubmit={handleSubmit} className="space-y-4"> useInvertedBackground={useInvertedBackground}
<input inputPlaceholder={inputPlaceholder}
type="email" buttonText={buttonText}
placeholder="your@email.com" termsText={termsText}
value={email} onSubmit={handleSubmit}
onChange={(e) => setEmail(e.target.value)} centered={true}
className="w-full px-4 py-2 border rounded-lg" tagClassName={tagClassName}
required titleClassName={titleClassName}
/> descriptionClassName={descriptionClassName}
<button type="submit" className="w-full px-4 py-2 bg-primary text-white rounded-lg"> formWrapperClassName={cls("md:w-8/10 2xl:w-6/10", formWrapperClassName)}
Send formClassName={formClassName}
</button> inputClassName={inputClassName}
</form> buttonClassName={buttonClassName}
buttonTextClassName={buttonTextClassName}
{contactEmail && <p className="mt-6 text-sm text-muted-foreground">Email: {contactEmail}</p>} termsClassName={termsClassName}
{contactPhone && <p className="text-sm text-muted-foreground">Phone: {contactPhone}</p>} />
</div> </div>
</div> <div className="absolute inset w-full h-full z-0 rounded-theme-capped overflow-hidden" >
); <HeroBackgrounds {...background} />
</div>
</div>
</div>
</section>
);
}; };
ContactCenter.displayName = "ContactCenter";
export default ContactCenter; export default ContactCenter;

View File

@@ -1,10 +1,14 @@
"use client";
import React, { useState } from "react"; import React, { useState } from "react";
import { cn } from "@/lib/utils"; import { Mail } from "lucide-react";
export interface ContactSplitProps { export interface ContactSplitProps {
tag?: string; tag: string;
title: string; title: string;
description: string; description: string;
tagIcon?: React.ComponentType<any>;
tagAnimation?: "none" | "opacity" | "slide-up" | "blur-reveal";
background?: { variant: string }; background?: { variant: string };
useInvertedBackground?: boolean; useInvertedBackground?: boolean;
imageSrc?: string; imageSrc?: string;
@@ -17,10 +21,10 @@ export interface ContactSplitProps {
buttonText?: string; buttonText?: string;
termsText?: string; termsText?: string;
onSubmit?: (email: string) => void; onSubmit?: (email: string) => void;
ariaLabel?: string;
className?: string; className?: string;
containerClassName?: string; containerClassName?: string;
contentClassName?: string; contentClassName?: string;
contactFormClassName?: string;
tagClassName?: string; tagClassName?: string;
titleClassName?: string; titleClassName?: string;
descriptionClassName?: string; descriptionClassName?: string;
@@ -34,90 +38,107 @@ export interface ContactSplitProps {
mediaClassName?: string; mediaClassName?: string;
} }
export const ContactSplit: React.FC<ContactSplitProps> = ({ const ContactSplit = React.forwardRef<HTMLDivElement, ContactSplitProps>(
tag, (
title, {
description, tag,
imageSrc, title,
videoSrc, description,
imageAlt = "", mediaPosition = "right", inputPlaceholder = "Enter your email", buttonText = "Sign Up", termsText, tagIcon: TagIcon,
useInvertedBackground = false, tagAnimation = "none", background,
className, useInvertedBackground = false,
containerClassName, imageSrc,
contentClassName, videoSrc,
tagClassName, imageAlt = "", videoAriaLabel = "Contact section video", mediaAnimation = "none", mediaPosition = "right", inputPlaceholder = "Enter your email", buttonText = "Sign Up", termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.", onSubmit,
titleClassName, ariaLabel = "Contact section", className = "", containerClassName = "", contentClassName = "", tagClassName = "", titleClassName = "", descriptionClassName = "", formWrapperClassName = "", formClassName = "", inputClassName = "", buttonClassName = "", buttonTextClassName = "", termsClassName = "", mediaWrapperClassName = "", mediaClassName = ""},
descriptionClassName, ref
formWrapperClassName, ) => {
formClassName, const [email, setEmail] = useState("");
inputClassName,
buttonClassName,
buttonTextClassName,
termsClassName,
mediaWrapperClassName,
mediaClassName
}) => {
const [email, setEmail] = useState("");
const handleFormSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setEmail(""); onSubmit?.(email);
}; setEmail("");
};
return ( return (
<div <div
className={cn( ref={ref}
"w-full py-20 px-4", useInvertedBackground && "bg-accent/10", containerClassName className={`w-full py-20 ${className}`}
)} aria-label={ariaLabel}
> >
<div className={cn("max-w-6xl mx-auto", contentClassName)}> <div className={`max-w-7xl mx-auto px-4 ${containerClassName}`}>
<div className={cn("grid grid-cols-1 md:grid-cols-2 gap-12 items-center", className)}> <div className={`grid grid-cols-1 md:grid-cols-2 gap-12 ${contentClassName}`}>
{mediaPosition === "left" && imageSrc && ( {/* Text Content */}
<div className={cn("order-first", mediaWrapperClassName)}> <div className={formWrapperClassName}>
<img src={imageSrc} alt={imageAlt} className={cn("w-full rounded-lg", mediaClassName)} /> {tag && (
</div> <div className={`flex items-center gap-2 mb-4 ${tagClassName}`}>
)} {TagIcon && <TagIcon className="w-4 h-4" />}
<span className="text-sm font-medium">{tag}</span>
</div>
)}
<h2 className={`text-4xl font-bold mb-4 ${titleClassName}`}>
{title}
</h2>
<p
className={`text-lg text-foreground/75 mb-8 ${descriptionClassName}`}
>
{description}
</p>
<div className={cn("space-y-6", contactFormClassName)}> <form
{tag && <p className={cn("text-sm font-semibold text-accent", tagClassName)}>{tag}</p>} onSubmit={handleSubmit}
<h2 className={cn("text-4xl font-bold", titleClassName)}>{title}</h2> className={`space-y-4 ${formClassName}`}
<p className={cn("text-lg text-muted-foreground", descriptionClassName)}>{description}</p> >
<form onSubmit={handleFormSubmit} className={cn("space-y-4", formWrapperClassName)}>
<div className={cn("space-y-2", formClassName)}>
<input <input
type="email" type="email"
placeholder={inputPlaceholder}
value={email} value={email}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
className={cn( placeholder={inputPlaceholder}
"w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary", inputClassName
)}
required required
className={`w-full px-4 py-3 bg-secondary-cta text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-cta ${inputClassName}`}
/> />
<button <button
type="submit" type="submit"
className={cn( className={`w-full px-4 py-3 bg-primary-cta text-primary-cta-text font-medium rounded-lg hover:opacity-90 transition-opacity ${buttonClassName}`}
"w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors", buttonClassName
)}
> >
<span className={buttonTextClassName}>{buttonText}</span> <span className={buttonTextClassName}>{buttonText}</span>
</button> </button>
</div> </form>
</form>
{termsText && <p className={cn("text-xs text-muted-foreground", termsClassName)}>{termsText}</p>} {termsText && (
</div> <p className={`text-xs text-foreground/60 mt-4 ${termsClassName}`}>
{termsText}
{mediaPosition === "right" && imageSrc && ( </p>
<div className={cn("order-last", mediaWrapperClassName)}> )}
<img src={imageSrc} alt={imageAlt} className={cn("w-full rounded-lg", mediaClassName)} />
</div> </div>
)}
{/* Media */}
{(imageSrc || videoSrc) && (
<div className={`flex items-center justify-center ${mediaWrapperClassName}`}>
{videoSrc ? (
<video
src={videoSrc}
aria-label={videoAriaLabel}
controls
className={`w-full h-full object-cover rounded-lg ${mediaClassName}`}
/>
) : imageSrc ? (
<img
src={imageSrc}
alt={imageAlt}
className={`w-full h-full object-cover rounded-lg ${mediaClassName}`}
/>
) : null}
</div>
)}
</div>
</div> </div>
</div> </div>
</div> );
); }
}; );
ContactSplit.displayName = "ContactSplit";
export default ContactSplit; export default ContactSplit;

View File

@@ -1,59 +1,214 @@
import React, { useState } from "react"; "use client";
import { cn } from "@/lib/utils";
export interface ContactSplitFormProps { import { useState } from "react";
tag?: string; import TextAnimation from "@/components/text/TextAnimation";
title: string; import Button from "@/components/button/Button";
description: string; import Input from "@/components/form/Input";
useInvertedBackground?: boolean; import Textarea from "@/components/form/Textarea";
inputPlaceholder?: string; import MediaContent from "@/components/shared/MediaContent";
buttonText?: string; import { cls, shouldUseInvertedText } from "@/lib/utils";
className?: string; import { useTheme } from "@/providers/themeProvider/ThemeProvider";
containerClassName?: string; 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 const ContactSplitForm: React.FC<ContactSplitFormProps> = ({ export interface TextareaField {
tag, name: string;
title, placeholder: string;
description, rows?: number;
useInvertedBackground = false, required?: boolean;
inputPlaceholder = "Enter your email", buttonText = "Sign Up", className, className?: string;
containerClassName }
}) => {
const [email, setEmail] = useState("");
const handleSubmit = (e: React.FormEvent) => { interface ContactSplitFormProps {
e.preventDefault(); title: string;
setEmail(""); 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;
}
return ( const ContactSplitForm = ({
<div title,
className={cn( description,
"w-full py-20 px-4", useInvertedBackground && "bg-accent/10", containerClassName inputs,
)} textarea,
> useInvertedBackground,
<div className={cn("max-w-2xl mx-auto text-center space-y-6", className)}> imageSrc,
{tag && <p className="text-sm font-semibold text-accent">{tag}</p>} videoSrc,
<h2 className="text-4xl font-bold">{title}</h2> imageAlt = "",
<p className="text-lg text-muted-foreground">{description}</p> 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 });
<form onSubmit={handleSubmit} className="space-y-4"> // Validate minimum inputs requirement
<input if (inputs.length < 2) {
type="email" throw new Error("ContactSplitForm requires at least 2 inputs");
placeholder={inputPlaceholder} }
value={email}
onChange={(e) => setEmail(e.target.value)} // Initialize form data dynamically
className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary" const initialFormData: Record<string, string> = {};
required inputs.forEach(input => {
/> initialFormData[input.name] = "";
<button type="submit" className="w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"> });
{buttonText} if (textarea) {
</button> initialFormData[textarea.name] = "";
</form> }
</div>
</div> 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>
);
}; };
ContactSplitForm.displayName = "ContactSplitForm";
export default ContactSplitForm; export default ContactSplitForm;

View File

@@ -1,100 +1,248 @@
import React from "react"; "use client";
import { cn } from "@/lib/utils";
export interface PricingPlan { import { memo } from "react";
id: string; import CardStack from "@/components/cardStack/CardStack";
badge: string; import Button from "@/components/button/Button";
price: string; import PricingBadge from "@/components/shared/PricingBadge";
subtitle: string; import PricingFeatureList from "@/components/shared/PricingFeatureList";
buttons: Array<{ text: string; onClick?: () => void; href?: string }>; import { getButtonProps } from "@/lib/buttonUtils";
features: string[]; 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";
export interface PricingCardEightProps { type PricingPlan = {
plans: PricingPlan[]; id: string;
title: string; badge: string;
description: string; badgeIcon?: LucideIcon;
animationType?: "none" | "opacity" | "slide-up" | "scale-rotate" | "blur-reveal"; price: string;
textboxLayout?: "default" | "split" | "split-actions" | "split-description" | "inline-image"; subtitle: string;
useInvertedBackground?: boolean; buttons: ButtonConfig[];
className?: string; features: string[];
containerClassName?: string;
cardClassName?: string;
badgeClassName?: string;
priceClassName?: string;
subtitleClassName?: string;
planButtonContainerClassName?: string;
planButtonClassName?: string;
featuresClassName?: string;
featureItemClassName?: string;
gridClassName?: string;
textBoxClassName?: string;
}
export const PricingCardEight: React.FC<PricingCardEightProps> = ({
plans,
title,
description,
animationType = "slide-up", textboxLayout = "default", useInvertedBackground = false,
className,
containerClassName,
cardClassName,
badgeClassName,
priceClassName,
subtitleClassName,
planButtonContainerClassName,
planButtonClassName,
featuresClassName,
featureItemClassName,
gridClassName,
textBoxClassName
}) => {
return (
<div className={cn("w-full py-20 px-4", containerClassName)}>
<div className={cn("max-w-6xl mx-auto", className)}>
<div className={cn("text-center mb-12 space-y-4", textBoxClassName)}>
<h2 className="text-4xl font-bold">{title}</h2>
<p className="text-lg text-muted-foreground">{description}</p>
</div>
<div className={cn("grid grid-cols-1 md:grid-cols-3 gap-8", gridClassName)}>
{plans.map((plan) => (
<div key={plan.id} className={cn("border rounded-lg p-6 space-y-6", cardClassName)}>
<div className="space-y-4">
<span className={cn("inline-block text-sm font-semibold px-3 py-1 bg-primary/10 rounded-full", badgeClassName)}> {plan.badge}
</span>
<h3 className={cn("text-3xl font-bold", priceClassName)}>{plan.price}</h3>
<p className={cn("text-muted-foreground", subtitleClassName)}>{plan.subtitle}</p>
</div>
<div className={cn("space-y-3", planButtonContainerClassName)}>
{plan.buttons.map((button, idx) => (
<button
key={idx}
onClick={button.onClick}
className={cn(
"w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors", planButtonClassName
)}
>
{button.text}
</button>
))}
</div>
<div className={cn("space-y-2", featuresClassName)}>
{plan.features.map((feature, idx) => (
<div key={idx} className={cn("flex items-center gap-2", featureItemClassName)}>
<span className="text-primary"></span>
<span className="text-sm">{feature}</span>
</div>
))}
</div>
</div>
))}
</div>
</div>
</div>
);
}; };
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;
}
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}
/>
))}
</CardStack>
);
};
PricingCardEight.displayName = "PricingCardEight";
export default PricingCardEight; export default PricingCardEight;

View File

@@ -1,238 +1,103 @@
"use client"; "use client";
import { memo, useCallback } from "react"; import React from "react";
import { useRouter } from "next/navigation"; import { Heart } 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 ProductCardFourGridVariant = Exclude<GridVariant, "timeline" | "items-top-row-full-width-bottom" | "full-width-top-items-bottom-row">; export interface ProductCard {
id: string;
name: string;
price: string;
imageSrc: string;
imageAlt?: string;
category?: string;
rating?: number;
reviewCount?: string;
isFavorited?: boolean;
}
type ProductCard = Product & { export interface ProductCardFourProps {
variant: string; products: ProductCard[];
}; title?: string;
description?: string;
interface ProductCardFourProps { onFavorite?: (productId: string) => void;
products?: ProductCard[];
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; 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; gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
}
interface ProductCardItemProps {
product: ProductCard;
shouldUseLightText: boolean;
cardClassName?: string; cardClassName?: string;
imageClassName?: string;
cardNameClassName?: string;
cardPriceClassName?: string;
cardVariantClassName?: string;
actionButtonClassName?: string;
} }
const ProductCardItem = memo(({ const ProductCardFour = React.forwardRef<
product, HTMLDivElement,
shouldUseLightText, ProductCardFourProps
cardClassName = "", >((
imageClassName = "", {
cardNameClassName = "", products,
cardPriceClassName = "", title,
cardVariantClassName = "", description,
actionButtonClassName = "", onFavorite,
}: ProductCardItemProps) => { className = "", gridClassName = "", cardClassName = ""},
ref
) => {
return ( return (
<article <div ref={ref} className={`w-full ${className}`}>
className={cls("card group relative h-full flex flex-col gap-4 cursor-pointer p-4 rounded-theme-capped", cardClassName)} {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
onClick={product.onProductClick} {description && (
role="article" <p className="text-base text-foreground/75 mb-8">{description}</p>
aria-label={`${product.name} - ${product.price}`} )}
> <div className={`grid grid-cols-1 gap-6 ${gridClassName}`}>
<ProductImage {products.map((product) => (
imageSrc={product.imageSrc} <div
imageAlt={product.imageAlt || product.name} key={product.id}
isFavorited={product.isFavorited} className={`relative overflow-hidden rounded-lg ${cardClassName}`}
onFavoriteToggle={product.onFavorite} >
showActionButton={true} {/* Image Container */}
actionButtonAriaLabel={`View ${product.name} details`} <div className="relative aspect-square bg-card overflow-hidden">
imageClassName={imageClassName} {product.imageSrc && (
actionButtonClassName={actionButtonClassName} <img
/> src={product.imageSrc}
alt={product.imageAlt || product.name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
)}
{/* Favorite Button */}
<button
onClick={() => onFavorite?.(product.id)}
className="absolute top-4 right-4 p-2 rounded-full bg-white/80 hover:bg-white transition-colors"
aria-label="Add to favorites"
>
<Heart
className="w-5 h-5"
fill={product.isFavorited ? "currentColor" : "none"}
/>
</button>
</div>
<div className="flex flex-col gap-2"> {/* Product Info */}
<div className="flex items-center justify-between gap-4"> <div className="p-4">
<div className="flex flex-col gap-0 flex-1 min-w-0"> {product.category && (
<h3 className={cls("text-base font-medium leading-[1.3]", shouldUseLightText ? "text-background" : "text-foreground", cardNameClassName)}> <p className="text-xs font-medium text-primary-cta mb-2">
{product.name} {product.category}
</h3> </p>
<p className={cls("text-sm leading-[1.3]", shouldUseLightText ? "text-background/60" : "text-foreground/60", cardVariantClassName)}> )}
{product.variant} <h3 className="font-semibold mb-2 line-clamp-2">{product.name}</h3>
</p> {product.rating !== undefined && (
<div className="flex items-center gap-2 mb-2">
<span className="text-sm"> {product.rating}</span>
{product.reviewCount && (
<span className="text-xs text-foreground/60">
({product.reviewCount})
</span>
)}
</div>
)}
<p className="font-bold text-lg">{product.price}</p>
</div>
</div> </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> </div>
</article> </div>
); );
}); });
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"; ProductCardFour.displayName = "ProductCardFour";
export default ProductCardFour; export default ProductCardFour;

View File

@@ -1,225 +1,99 @@
"use client"; "use client";
import { memo, useCallback } from "react"; import React from "react";
import { useRouter } from "next/navigation"; import { Heart } from "lucide-react";
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">; export interface Product {
id: string;
type ProductCard = Product; name: string;
price: string;
interface ProductCardOneProps { imageSrc: string;
products?: ProductCard[]; imageAlt?: string;
carouselMode?: "auto" | "buttons"; category?: string;
gridVariant: ProductCardOneGridVariant; rating?: number;
uniformGridCustomHeightClasses?: string; reviewCount?: string;
animationType: CardAnimationType; isFavorited?: boolean;
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;
gridClassName?: string;
carouselClassName?: string;
controlsClassName?: string;
textBoxClassName?: string;
textBoxTagClassName?: string;
textBoxButtonContainerClassName?: string;
textBoxButtonClassName?: string;
textBoxButtonTextClassName?: string;
} }
interface ProductCardItemProps { export interface ProductCardOneProps {
product: ProductCard; products: Product[];
shouldUseLightText: boolean; title?: string;
cardClassName?: string; description?: string;
imageClassName?: string; onFavorite?: (productId: string) => void;
cardNameClassName?: string; className?: string;
cardPriceClassName?: string; gridClassName?: string;
cardClassName?: string;
} }
const ProductCardItem = memo(({ const ProductCardOne = React.forwardRef<HTMLDivElement, ProductCardOneProps>((
product, {
shouldUseLightText, products,
cardClassName = "",
imageClassName = "",
cardNameClassName = "",
cardPriceClassName = "",
}: 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.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, title,
titleSegments,
description, description,
tag, onFavorite,
tagIcon, className = "", gridClassName = "", cardClassName = ""},
tagAnimation, ref
buttons, ) => {
buttonAnimation, return (
textboxLayout, <div ref={ref} className={`w-full ${className}`}>
useInvertedBackground, {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
ariaLabel = "Product section", {description && (
className = "", <p className="text-base text-foreground/75 mb-8">{description}</p>
containerClassName = "", )}
cardClassName = "", <div className={`grid grid-cols-1 gap-6 ${gridClassName}`}>
imageClassName = "", {products.map((product) => (
textBoxTitleClassName = "", <div
textBoxTitleImageWrapperClassName = "", key={product.id}
textBoxTitleImageClassName = "", className={`relative overflow-hidden rounded-lg ${cardClassName}`}
textBoxDescriptionClassName = "", >
cardNameClassName = "", {/* Image Container */}
cardPriceClassName = "", <div className="relative aspect-square bg-card overflow-hidden">
gridClassName = "", {product.imageSrc && (
carouselClassName = "", <img
controlsClassName = "", src={product.imageSrc}
textBoxClassName = "", alt={product.imageAlt || product.name}
textBoxTagClassName = "", className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
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> {/* Favorite Button */}
); <button
}; onClick={() => onFavorite?.(product.id)}
className="absolute top-4 right-4 p-2 rounded-full bg-white/80 hover:bg-white transition-colors"
aria-label="Add to favorites"
>
<Heart
className="w-5 h-5"
fill={product.isFavorited ? "currentColor" : "none"}
/>
</button>
</div>
{/* Product Info */}
<div className="p-4">
{product.category && (
<p className="text-xs font-medium text-primary-cta mb-2">
{product.category}
</p>
)}
<h3 className="font-semibold mb-2 line-clamp-2">{product.name}</h3>
{product.rating !== undefined && (
<div className="flex items-center gap-2 mb-2">
<span className="text-sm"> {product.rating}</span>
{product.reviewCount && (
<span className="text-xs text-foreground/60">
({product.reviewCount})
</span>
)}
</div>
)}
<p className="font-bold text-lg">{product.price}</p>
</div>
</div>
))}
</div>
</div>
);
});
ProductCardOne.displayName = "ProductCardOne"; ProductCardOne.displayName = "ProductCardOne";

View File

@@ -1,282 +1,102 @@
"use client"; "use client";
import { memo, useState, useCallback } from "react"; import React from "react";
import { useRouter } from "next/navigation"; import { Heart } from "lucide-react";
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">; export interface ProductCard {
id: string;
type ProductCard = Product & { name: string;
onQuantityChange?: (quantity: number) => void; price: string;
initialQuantity?: number; imageSrc: string;
priceButtonProps?: Partial<ButtonPropsForVariant<CTAButtonVariant>>; imageAlt?: string;
}; category?: string;
rating?: number;
interface ProductCardThreeProps { reviewCount?: string;
products?: ProductCard[]; isFavorited?: boolean;
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;
} }
export interface ProductCardThreeProps {
interface ProductCardItemProps { products: ProductCard[];
product: ProductCard; title?: string;
shouldUseLightText: boolean; description?: string;
isFromApi: boolean; onFavorite?: (productId: string) => void;
onBuyClick?: (productId: string, quantity: number) => void; className?: string;
cardClassName?: string; gridClassName?: string;
imageClassName?: string; cardClassName?: string;
cardNameClassName?: string;
quantityControlsClassName?: string;
} }
const ProductCardItem = memo(({ const ProductCardThree = React.forwardRef<
product, HTMLDivElement,
shouldUseLightText, ProductCardThreeProps
isFromApi, >((
onBuyClick, {
cardClassName = "", products,
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, title,
titleSegments,
description, description,
tag, onFavorite,
tagIcon, className = "", gridClassName = "", cardClassName = ""},
tagAnimation, ref
buttons, ) => {
buttonAnimation, return (
textboxLayout, <div ref={ref} className={`w-full ${className}`}>
useInvertedBackground, {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
ariaLabel = "Product section", {description && (
className = "", <p className="text-base text-foreground/75 mb-8">{description}</p>
containerClassName = "", )}
cardClassName = "", <div className={`grid grid-cols-1 gap-6 ${gridClassName}`}>
imageClassName = "", {products.map((product) => (
textBoxTitleClassName = "", <div
textBoxTitleImageWrapperClassName = "", key={product.id}
textBoxTitleImageClassName = "", className={`relative overflow-hidden rounded-lg ${cardClassName}`}
textBoxDescriptionClassName = "", >
cardNameClassName = "", {/* Image Container */}
quantityControlsClassName = "", <div className="relative aspect-square bg-card overflow-hidden">
gridClassName = "", {product.imageSrc && (
carouselClassName = "", <img
controlsClassName = "", src={product.imageSrc}
textBoxClassName = "", alt={product.imageAlt || product.name}
textBoxTagClassName = "", className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
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> {/* Favorite Button */}
); <button
}; onClick={() => onFavorite?.(product.id)}
className="absolute top-4 right-4 p-2 rounded-full bg-white/80 hover:bg-white transition-colors"
aria-label="Add to favorites"
>
<Heart
className="w-5 h-5"
fill={product.isFavorited ? "currentColor" : "none"}
/>
</button>
</div>
{/* Product Info */}
<div className="p-4">
{product.category && (
<p className="text-xs font-medium text-primary-cta mb-2">
{product.category}
</p>
)}
<h3 className="font-semibold mb-2 line-clamp-2">{product.name}</h3>
{product.rating !== undefined && (
<div className="flex items-center gap-2 mb-2">
<span className="text-sm"> {product.rating}</span>
{product.reviewCount && (
<span className="text-xs text-foreground/60">
({product.reviewCount})
</span>
)}
</div>
)}
<p className="font-bold text-lg">{product.price}</p>
</div>
</div>
))}
</div>
</div>
);
});
ProductCardThree.displayName = "ProductCardThree"; ProductCardThree.displayName = "ProductCardThree";

View File

@@ -1,266 +1,99 @@
"use client"; "use client";
import { memo, useCallback } from "react"; import React from "react";
import { useRouter } from "next/navigation"; import { Heart } from "lucide-react";
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">; export interface ProductCard {
id: string;
type ProductCard = Product & { name: string;
brand: string; price: string;
rating: number; imageSrc: string;
reviewCount: string; imageAlt?: string;
}; category?: string;
rating?: number;
interface ProductCardTwoProps { reviewCount?: string;
products?: ProductCard[]; isFavorited?: boolean;
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 { export interface ProductCardTwoProps {
product: ProductCard; products: ProductCard[];
shouldUseLightText: boolean; title?: string;
cardClassName?: string; description?: string;
imageClassName?: string; onFavorite?: (productId: string) => void;
cardBrandClassName?: string; className?: string;
cardNameClassName?: string; gridClassName?: string;
cardPriceClassName?: string; cardClassName?: string;
cardRatingClassName?: string;
actionButtonClassName?: string;
} }
const ProductCardItem = memo(({ const ProductCardTwo = React.forwardRef<HTMLDivElement, ProductCardTwoProps>((
product, {
shouldUseLightText, products,
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, title,
titleSegments,
description, description,
tag, onFavorite,
tagIcon, className = "", gridClassName = "", cardClassName = ""},
tagAnimation, ref
buttons, ) => {
buttonAnimation, return (
textboxLayout, <div ref={ref} className={`w-full ${className}`}>
useInvertedBackground, {title && <h2 className="text-3xl font-bold mb-4">{title}</h2>}
ariaLabel = "Product section", {description && (
className = "", <p className="text-base text-foreground/75 mb-8">{description}</p>
containerClassName = "", )}
cardClassName = "", <div className={`grid grid-cols-1 gap-6 ${gridClassName}`}>
imageClassName = "", {products.map((product) => (
textBoxTitleClassName = "", <div
textBoxTitleImageWrapperClassName = "", key={product.id}
textBoxTitleImageClassName = "", className={`relative overflow-hidden rounded-lg ${cardClassName}`}
textBoxDescriptionClassName = "", >
cardBrandClassName = "", {/* Image Container */}
cardNameClassName = "", <div className="relative aspect-square bg-card overflow-hidden">
cardPriceClassName = "", {product.imageSrc && (
cardRatingClassName = "", <img
actionButtonClassName = "", src={product.imageSrc}
gridClassName = "", alt={product.imageAlt || product.name}
carouselClassName = "", className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
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> {/* Favorite Button */}
); <button
}; onClick={() => onFavorite?.(product.id)}
className="absolute top-4 right-4 p-2 rounded-full bg-white/80 hover:bg-white transition-colors"
aria-label="Add to favorites"
>
<Heart
className="w-5 h-5"
fill={product.isFavorited ? "currentColor" : "none"}
/>
</button>
</div>
{/* Product Info */}
<div className="p-4">
{product.category && (
<p className="text-xs font-medium text-primary-cta mb-2">
{product.category}
</p>
)}
<h3 className="font-semibold mb-2 line-clamp-2">{product.name}</h3>
{product.rating !== undefined && (
<div className="flex items-center gap-2 mb-2">
<span className="text-sm"> {product.rating}</span>
{product.reviewCount && (
<span className="text-xs text-foreground/60">
({product.reviewCount})
</span>
)}
</div>
)}
<p className="font-bold text-lg">{product.price}</p>
</div>
</div>
))}
</div>
</div>
);
});
ProductCardTwo.displayName = "ProductCardTwo"; ProductCardTwo.displayName = "ProductCardTwo";

View File

@@ -1,62 +1,117 @@
"use client";
import { useState } from "react"; import { useState } from "react";
import { Product } from "@/lib/api/product";
export interface CartItem { export type CheckoutItem = {
id: string; productId: string;
name: string; quantity: number;
price: number; imageSrc?: string;
quantity: number; imageAlt?: string;
} metadata?: {
brand?: string;
export const useCheckout = () => { variant?: string;
const [cartItems, setCartItems] = useState<CartItem[]>([]); rating?: number;
const [isLoading, setIsLoading] = useState(false); reviewCount?: string;
const [error, setError] = useState<string | null>(null); [key: string]: string | number | undefined;
};
const addToCart = (item: CartItem) => {
setCartItems((prev) => {
const existing = prev.find((i) => i.id === item.id);
if (existing) {
return prev.map((i) => (i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i));
}
return [...prev, item];
});
};
const removeFromCart = (id: string) => {
setCartItems((prev) => prev.filter((item) => item.id !== id));
};
const updateQuantity = (id: string, quantity: number) => {
setCartItems((prev) =>
prev.map((item) => (item.id === id ? { ...item, quantity: Math.max(1, quantity) } : item))
);
};
const getTotal = () => {
return cartItems.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2);
};
const checkout = async () => {
setIsLoading(true);
try {
// Simulate checkout process
await new Promise((resolve) => setTimeout(resolve, 1000));
setCartItems([]);
} catch (err) {
setError(err instanceof Error ? err.message : "Checkout failed");
} finally {
setIsLoading(false);
}
};
return {
cartItems,
isLoading,
error,
addToCart,
removeFromCart,
updateQuantity,
getTotal,
checkout
};
}; };
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,18 @@
"use client"; import { useCallback } from "react";
import { fetchProducts } from "@/lib/api/product";
import { useEffect, useState } from "react"; export const useProduct = () => {
import { Product, fetchProduct } from "@/lib/api/product"; const getProducts = useCallback(async () => {
try {
const products = await fetchProducts();
return products;
} catch (error) {
console.error("Error fetching products:", error);
return [];
}
}, []);
export function useProduct(productId: string) { return {
const [product, setProduct] = useState<Product | null>(null); getProducts,
const [isLoading, setIsLoading] = useState(true); };
const [error, setError] = useState<Error | null>(null); };
useEffect(() => {
let isMounted = true;
async function loadProduct() {
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,35 +1,115 @@
import { useState, useEffect } from "react"; "use client";
export interface Product { import { useState, useMemo, useCallback } from "react";
id: string; import { useRouter } from "next/navigation";
name: string; import { useProducts } from "./useProducts";
price: number; import type { Product } from "@/lib/api/product";
category: string; import type { CatalogProduct } from "@/components/ecommerce/productCatalog/ProductCatalogItem";
description?: string; import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
export type SortOption = "Newest" | "Price: Low-High" | "Price: High-Low";
interface UseProductCatalogOptions {
basePath?: string;
} }
export const useProductCatalog = () => { export function useProductCatalog(options: UseProductCatalogOptions = {}) {
const [products, setProducts] = useState<Product[]>([]); const { basePath = "/shop" } = options;
const [isLoading, setIsLoading] = useState(true); const router = useRouter();
const [error, setError] = useState<string | null>(null); const { products: fetchedProducts, isLoading } = useProducts();
useEffect(() => { const [search, setSearch] = useState("");
const fetchProducts = async () => { const [category, setCategory] = useState("All");
try { const [sort, setSort] = useState<SortOption>("Newest");
setIsLoading(true);
// Simulate API call const handleProductClick = useCallback((productId: string) => {
await new Promise((resolve) => setTimeout(resolve, 500)); router.push(`${basePath}/${productId}`);
// Mock data would be loaded here }, [router, basePath]);
setProducts([]);
} catch (err) { const catalogProducts: CatalogProduct[] = useMemo(() => {
setError(err instanceof Error ? err.message : "Failed to load products"); if (fetchedProducts.length === 0) return [];
} finally {
setIsLoading(false); 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),
}));
}, [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,
}; };
}
fetchProducts();
}, []);
return { products, isLoading, error };
};

View File

@@ -1,37 +1,196 @@
import { useState, useEffect } from "react"; "use client";
export interface Product { import { useState, useMemo, useCallback } from "react";
id: string; import { useProduct } from "./useProduct";
name: string; import type { Product } from "@/lib/api/product";
price: number; import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
category: string; import type { ExtendedCartItem } from "./useCart";
description?: string;
interface ProductImage {
src: string;
alt: string;
} }
export const useProductDetail = (productId: string | undefined) => { interface ProductMeta {
const [product, setProduct] = useState<Product | null>(null); salePrice?: string;
const [isLoading, setIsLoading] = useState(true); ribbon?: string;
const [error, setError] = useState<string | null>(null); inventoryStatus?: string;
inventoryQuantity?: number;
sku?: string;
}
useEffect(() => { export function useProductDetail(productId: string) {
if (!productId) return; const { product, isLoading, error } = useProduct(productId);
const [selectedQuantity, setSelectedQuantity] = useState(1);
const [selectedVariants, setSelectedVariants] = useState<Record<string, string>>({});
const fetchProduct = async () => { const images = useMemo<ProductImage[]>(() => {
try { if (!product) return [];
setIsLoading(true);
// Simulate API call if (product.images && product.images.length > 0) {
await new Promise((resolve) => setTimeout(resolve, 500)); return product.images.map((src, index) => ({
// Product would be fetched here src,
setProduct(null); alt: product.imageAlt || `${product.name} - Image ${index + 1}`,
} catch (err) { }));
setError(err instanceof Error ? err.message : "Failed to load product"); }
} finally { return [{
setIsLoading(false); 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,
};
}, [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,
}; };
}
fetchProduct();
}, [productId]);
return { product, isLoading, error };
};

View File

@@ -1,34 +1,219 @@
export interface Product { export type Product = {
id: string; id: string;
name: string; name: string;
price: number; price: string;
category: 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: "/placeholders/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: "/placeholders/placeholder4.webp",
imageAlt: "Brown leather crossbody bag",
},
{
id: "3",
name: "Wireless Headphones",
price: "$199",
brand: "Sony",
variant: "Black",
rating: 4.7,
reviewCount: "512",
imageSrc: "/placeholders/placeholder3.avif",
imageAlt: "Black wireless headphones",
},
{
id: "4",
name: "Minimalist Watch",
price: "$249",
brand: "Fossil",
variant: "Silver / 40mm",
rating: 4.6,
reviewCount: "89",
imageSrc: "/placeholders/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 const fetchProducts = async (): Promise<Product[]> => { export async function fetchProducts(): Promise<Product[]> {
try { const apiUrl = process.env.NEXT_PUBLIC_API_URL;
// Simulate API call const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch {
console.error("Failed to fetch products");
return [];
}
};
export const fetchProductById = async (id: string): Promise<Product | null> => { if (!apiUrl || !projectId) {
try { return [];
const response = await fetch(`/api/products/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} }
return await response.json();
} catch { try {
console.error("Failed to fetch product"); const url = `${apiUrl}/stripe/project/products?projectId=${projectId}&expandDefaultPrice=true`;
return null; 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 || "/placeholders/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 || "/placeholders/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;
}
}