import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button } from './ui/button';
import { Card, CardContent } from './ui/card';
import { Badge } from './ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import { ImageWithFallback } from './figma/ImageWithFallback';
import { CTABannerSection } from './CTABannerSection';
import { useCart } from './CartContext';
import {
Calendar,
Clock,
ChevronUp,
Bookmark,
Twitter,
Facebook,
Linkedin,
Link,
Heart,
Eye,
BookOpen,
ArrowLeft
} from 'lucide-react';
import { useGetBlogByIDQuery, useGetBlogsQuery } from '../redux/services/blogApi';
import { FullScreenLoader } from './FullScreenLoader';
import { extractIdFromSlug, extractSlugFromSlugAndId, getSlugWithId } from '../utils/urlHelpers';
interface BlogDetailProps {
params?: {
slugAndId?: string;
};
}
export function BlogDetail({ params }: BlogDetailProps) {
const { slugAndId } = useParams<{ slugAndId: string }>();
const navigate = useNavigate();
const [scrollProgress, setScrollProgress] = useState(0);
const [showBackToTop, setShowBackToTop] = useState(false);
const [isLiked, setIsLiked] = useState(false);
const [isBookmarked, setIsBookmarked] = useState(false);
const { addToCart } = useCart();
// Extract full ID from URL using the new function
const fullId = slugAndId ? extractIdFromSlug(slugAndId) : null;
const urlSlug = slugAndId ? extractSlugFromSlugAndId(slugAndId) : '';
// Fetch blog details by ID directly - no dependency on list API
const {
data: blogPost,
isLoading: isLoadingBlog,
isError: isBlogError,
refetch: refetchBlog
} = useGetBlogByIDQuery(fullId as string, {
skip: !fullId,
refetchOnMountOrArgChange: true,
});
// Fetch related blogs (excluding current blog)
const {
data: relatedBlogsData,
isLoading: isLoadingRelated
} = useGetBlogsQuery({
limit: 3,
offset: 0,
content_status: 'publish',
content_type: 'BLOG',
}, {
skip: !fullId,
});
// SEO: Check if URL slug matches the actual slug_name and redirect if needed
useEffect(() => {
if (blogPost && fullId) {
// Get the expected slug from the blog post
const expectedSlug = blogPost.slug_name;
// Create the expected URL with proper formatting
const expectedUrl = getSlugWithId(expectedSlug, fullId);
// Get the current URL slug
const currentSlugAndId = slugAndId || '';
// Compare (case-insensitive)
if (currentSlugAndId.toLowerCase() !== expectedUrl.toLowerCase()) {
// Redirect to the correct URL
navigate(`/learning/articles/${expectedUrl}`, { replace: true });
}
}
}, [blogPost, fullId, slugAndId, navigate]);
useEffect(() => {
if (blogPost?.title) {
document.title = `${blogPost.title} | KLC Blog`;
}
window.scrollTo(0, 0);
const handleScroll = () => {
const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = (winScroll / height) * 100;
setScrollProgress(scrolled);
setShowBackToTop(winScroll > 300);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [blogPost?.title]);
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
};
const handleShare = (platform: string) => {
const url = window.location.href;
const title = blogPost?.title || '';
const shareUrls = {
twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`,
facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
copy: url
};
if (platform === 'copy') {
navigator.clipboard.writeText(url);
alert('Link copied to clipboard!');
} else {
window.open(shareUrls[platform as keyof typeof shareUrls], '_blank', 'width=600,height=400');
}
};
const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
};
// Calculate read time based on content length (approx)
const calculateReadTime = (content: string): string => {
const wordsPerMinute = 200;
const wordCount = content.split(/\s+/).length;
const minutes = Math.ceil(wordCount / wordsPerMinute);
return `${minutes} min read`;
};
// Filter related blogs (exclude current blog)
const relatedPosts = relatedBlogsData?.data?.items
?.filter((blog: any) => blog.id !== fullId)
.map((blog: any) => ({
id: blog.id,
title: blog.title,
slug: blog.slug_name,
excerpt: blog.short_description || blog.content.substring(0, 150) + '...',
author: blog.author_name || 'KLC Team',
publishedDate: blog.updated_at,
readTime: calculateReadTime(blog.content),
category: blog.content_category,
image: blog.banner_img || 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=400&h=300&fit=crop'
})) || [];
// Handle related post click - use full UUID
const handleRelatedPostClick = (postSlug: string, postId: string) => {
const url = getSlugWithId(postSlug, postId);
navigate(`/learning/articles/${url}`);
};
// Handle loading state
if (isLoadingBlog) {
return (
);
}
// Handle error state
if (isBlogError || !blogPost) {
return (
Article Not Found
The article you're looking for could not be found. It may have been moved or removed.
navigate('/learning/articles')}>
Back to Articles
);
}
return (
{/* Scroll Progress Bar */}
{/* Back to Top Button */}
{showBackToTop && (
)}
{/* Consistent Side Gutters - Breadcrumb Navigation */}
navigate('/learning/articles')}
className="p-0 h-auto font-medium hover:bg-transparent transition-colors"
style={{ color: '#6F6F6F' }}
>
Back to Articles
•
{blogPost.content_category || 'Article'}
{/* Main Content Container with Consistent Gutters */}
{/* Reading Width Constraint for Better Readability */}
{/* Hero Header - Improved Spacing */}
{/* Article Body with Enhanced Typography - Full Width */}
{/* Full Width Container - Uses complete available width */}
{/* Enhanced Tag Pills with Hover States */}
{blogPost.blog_tags && blogPost.blog_tags.length > 0 && (
Topics covered in this article
{blogPost.blog_tags.map((tag: any) => (
{tag.tag_name}
))}
)}
{/* Enhanced Author Bio Card */}
KLC
About KLC Team
The Kautilya Leadership Center team is dedicated to providing cutting-edge insights and research on leadership development, management strategies, and organizational excellence.
{/* Related Articles Section with Balanced Grid Layout */}
{relatedPosts.length > 0 && (
Explore More Leadership Insights
Discover additional strategies and frameworks to enhance your leadership effectiveness
{/* Balanced Card Grid with Equal Spacing */}
{relatedPosts.map((post: any) => (
{
// Use the same pattern as the main articles with full UUID
const url = getSlugWithId(post.slug, post.id);
navigate(`/learning/articles/${url}`);
}}
style={{ backgroundColor: '#FFFFFF' }}
>
{post.category}
{post.readTime}
{post.title}
{post.excerpt}
{post.author}
{formatDate(post.publishedDate)}
))}
)}
{/* CTA Section */}
);
}