ifixkart-storefront/components/FloatingButtons.tsx

91 lines
3.2 KiB
TypeScript

"use client";
import React, { useState, useEffect, useCallback } from 'react';
import { usePathname } from 'next/navigation';
import { ChevronUp } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useCartStore } from '@/store/cartStore';
/** Height of the fixed compare strip at the bottom (CompareBar: py-3 + 36px row + border). */
const COMPARE_BAR_HEIGHT_PX = 76;
export const FloatingButtons: React.FC = () => {
const [showScrollTop, setShowScrollTop] = useState(false);
/** Extra bottom offset so this button is never covered by fixed bottom bars. */
const [barOffset, setBarOffset] = useState(0);
const pathname = usePathname();
const compareList = useCartStore((s) => s.compareList) || [];
const hydrated = useCartStore((s) => s._hasHydrated);
const compareBarVisible =
hydrated && pathname !== '/compare' && compareList.length > 0;
const measure = useCallback(() => {
// PDP sticky purchase bar (rendered in ProductInteractiveGrid) — only counts
// while it is actually in the layout and visible.
const bar = document.querySelector<HTMLElement>('.sticky-purchase-bar');
const purchaseBarH =
bar && bar.offsetHeight > 0 && bar.getBoundingClientRect().height > 0
? bar.offsetHeight
: 0;
const compareH = compareBarVisible ? COMPARE_BAR_HEIGHT_PX : 0;
setBarOffset((prev) => {
const next = Math.max(purchaseBarH, compareH);
return prev === next ? prev : next;
});
}, [compareBarVisible]);
useEffect(() => {
const handleScroll = () => {
setShowScrollTop(window.scrollY > 400);
measure();
};
handleScroll();
window.addEventListener('scroll', handleScroll, { passive: true });
window.addEventListener('resize', measure, { passive: true });
return () => {
window.removeEventListener('scroll', handleScroll);
window.removeEventListener('resize', measure);
};
}, [measure]);
// Re-measure when the compare strip appears/disappears without scrolling.
useEffect(() => {
measure();
}, [measure]);
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};
return (
<div
className="fixed right-6 z-50 hidden sm:flex flex-col items-center gap-3"
style={{
bottom: `calc(${barOffset}px + max(1.5rem, env(safe-area-inset-bottom, 0px) + 0.75rem))`,
}}
>
{/* Scroll to Top — hidden on phones (<640px): fixed bottom bars live there,
and both iOS and Android scroll to top from the status bar. */}
<AnimatePresence>
{showScrollTop && (
<motion.button
initial={{ opacity: 0, scale: 0.8, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.8, y: 20 }}
whileHover={{ y: -3, scale: 1.05 }}
onClick={scrollToTop}
className="w-12 h-12 bg-white hover:bg-gray-50 text-gray-700 rounded-full shadow-soft hover:shadow-soft-hover border border-gray-100 flex items-center justify-center transition-colors"
title="Scroll to top"
>
<ChevronUp size={22} className="stroke-[2.5]" />
</motion.button>
)}
</AnimatePresence>
</div>
);
};