'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  AlertCircle,
  BookOpen,
  CheckCircle2,
  Download,
  FileText,
  Heart,
  Minus,
  Plus,
  RotateCcw,
  ShieldCheck,
  ShoppingBag,
  Sparkles,
  Tablet,
  Truck,
  Zap,
  ChevronRight,
  Clock,
} from 'lucide-react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import { addToCart } from '@/store/cartSlice';
import { showToast } from '@/components/common/Toast';
import api from '@/lib/api';
import { bookCoverUrl } from '@/lib/bookImage';
import { useRecentlyViewed } from '@/hooks/useRecentlyViewed';

type Attribute = { id: string; name: string; value: string };
type Image = { id: string; url: string; isPrimary: boolean; sortOrder: number; assetStatus: string };
type Catalogue = { id: string; title: string; pdfUrl: string; assetStatus: string };

export interface BookVariant {
  id: string;
  bookId: string;
  title?: string | null;
  format: 'HARDCOVER' | 'PAPERBACK' | 'EBOOK' | 'AUDIOBOOK' | string;
  isbn?: string | null;
  sku: string;
  barcode?: string | null;
  price: number;
  discountPrice?: number | null;
  stock: number;
  weight?: number | null;
  dimensions?: string | null;
  coverImage?: string | null;
  digitalFileUrl?: string | null;
  digitalFormat?: string | null;
  attributes?: any;
  isDefault: boolean;
  isActive: boolean;
}

interface Book {
  id: string;
  sourceProductId?: string | null;
  title: string;
  slug: string;
  price: number;
  discountPrice?: number | null;
  gstRate?: number;
  coverImage?: string | null;
  authorName?: string | null;
  publisherName?: string | null;
  categoryName?: string | null;
  language?: string | null;
  isbn?: string | null;
  sourceSku?: string | null;
  sku?: string | null;
  pages?: string | null;
  binding?: string | null;
  format?: string | null;
  edition?: string | null;
  publicationYear?: number | null;
  classGrade?: string | null;
  weight?: number | null;
  dimensions?: string | null;
  stock: number;
  description?: string | null;
  descriptionHtml?: string | null;
  additionalAttributesHtml?: string | null;
  attributes: Attribute[];
  images: Image[];
  variants: BookVariant[];
  catalogues: Catalogue[];
}

export default function BookDetailPage() {
  const params = useParams();
  const router = useRouter();
  const dispatch = useDispatch();
  const slug = params?.slug as string;
  const { isAuthenticated } = useSelector((state: RootState) => state.auth);
  const [book, setBook] = useState<Book | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [selectedVariantId, setSelectedVariantId] = useState<string | null>(null);
  const [selectedImage, setSelectedImage] = useState('');
  const [isInWishlist, setIsInWishlist] = useState(false);
  const [wishlistLoading, setWishlistLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'description' | 'specifications' | 'variants' | 'attributes' | 'catalogues'>('description');
  
  const { addId, recentlyViewed, fetchDetails } = useRecentlyViewed();

  // Smart Sales States
  const [fbtData, setFbtData] = useState<any>(null);
  const [selectedFbtIds, setSelectedFbtIds] = useState<string[]>([]);
  const [upsells, setUpsells] = useState<any[]>([]);

  useEffect(() => {
    if (book?.id) {
      addId(book.id);
    }
  }, [book?.id, addId]);

  useEffect(() => {
    fetchDetails();
  }, [book?.id, fetchDetails]);

  const otherRecentlyViewed = recentlyViewed.filter((b) => b.id !== book?.id);

  useEffect(() => {
    if (!slug) return;
    setLoading(true);
    setError('');
    api.get(`/books/${encodeURIComponent(slug)}`)
      .then((response) => {
        const value = response.data.data.book as Book;
        setBook(value);
        if (value.id) {
          addId(value.id);
        }
        setSelectedImage(value.coverImage || value.images?.[0]?.url || '');
        // Auto-select default variant or first variant if available
        if (value.variants && value.variants.length > 0) {
          const defaultVar = value.variants.find((v) => v.isDefault) || value.variants[0];
          setSelectedVariantId(defaultVar.id);
        }
        // Check wishlist status if authenticated
        if (isAuthenticated && value.id) {
          api.get('/wishlist').then((wishRes) => {
            const items = wishRes.data?.data?.items || [];
            const exists = items.some((item: any) => item.bookId === value.id);
            setIsInWishlist(exists);
          }).catch(() => {});
        }

        // Fetch Smart Sales Frequently Bought Together & Upsells
        if (value.id) {
          api.get(`/smart-sales/frequently-bought-together/${value.id}`).then((res) => {
            if (res.data?.data) {
              setFbtData(res.data.data);
              setSelectedFbtIds(res.data.data.items.map((i: any) => i.id));
            }
          }).catch(() => {});

          api.get(`/smart-sales/upsells/${value.id}`).then((res) => {
            if (res.data?.data?.upsells) {
              setUpsells(res.data.data.upsells);
            }
          }).catch(() => {});
        }
      })
      .catch((requestError) => {
        setBook(null);
        setError(requestError instanceof Error ? requestError.message : 'This product could not be loaded.');
      })
      .finally(() => setLoading(false));
  }, [slug, isAuthenticated]);

  const handleToggleWishlist = async () => {
    if (!book) return;
    if (!isAuthenticated) {
      showToast('Please sign in to save books to your wishlist', 'info');
      router.push(`/login?redirect=/books/${encodeURIComponent(slug)}`);
      return;
    }

    try {
      setWishlistLoading(true);
      const res = await api.post('/wishlist/toggle', { bookId: book.id });
      const inWishlist = res.data?.data?.isInWishlist ?? !isInWishlist;
      setIsInWishlist(inWishlist);
      showToast(res.data?.message || (inWishlist ? 'Added to wishlist' : 'Removed from wishlist'), inWishlist ? 'success' : 'info');
    } catch (err: any) {
      showToast(err?.response?.data?.message || 'Failed to update wishlist', 'error');
    } finally {
      setWishlistLoading(false);
    }
  };

  const activeVariant = useMemo(() => {
    if (!book || !book.variants || book.variants.length === 0) return null;
    return book.variants.find((v) => v.id === selectedVariantId) || book.variants[0] || null;
  }, [book, selectedVariantId]);

  const images = useMemo(() => {
    if (!book) return [];
    const variantImg = activeVariant?.coverImage;
    return Array.from(new Set([variantImg, book.coverImage, ...(book.images ?? []).map((image) => image.url)].filter(Boolean))) as string[];
  }, [book, activeVariant]);

  const currentPrice = activeVariant ? activeVariant.price : (book?.price ?? 0);
  const currentDiscountPrice = activeVariant ? activeVariant.discountPrice : (book?.discountPrice ?? null);
  const currentSellingPrice = currentDiscountPrice ?? currentPrice;
  const currentStock = activeVariant ? activeVariant.stock : (book?.stock ?? 0);
  const currentSku = activeVariant?.sku || book?.sku || book?.sourceSku || 'N/A';
  const currentIsbn = activeVariant?.isbn || book?.isbn || 'N/A';
  const isEbook = activeVariant?.format?.toUpperCase() === 'EBOOK';

  const addBookToCart = () => {
    if (!book || currentStock <= 0) return;
    dispatch(
      addToCart({
        id: activeVariant ? `${book.id}_${activeVariant.id}` : book.id,
        bookId: book.id,
        variantId: activeVariant?.id,
        format: activeVariant?.format || book.format || 'PAPERBACK',
        sku: currentSku,
        digitalFormat: activeVariant?.digitalFormat || undefined,
        title: activeVariant?.title || (activeVariant ? `${book.title} (${activeVariant.format})` : book.title),
        price: currentPrice,
        discountPrice: currentDiscountPrice ?? undefined,
        coverImage: activeVariant?.coverImage || book.coverImage || undefined,
        stock: currentStock,
        authorName: book.authorName || undefined,
        quantity,
      })
    );
    showToast(
      `Added ${quantity} × “${book.title} (${activeVariant?.format || 'Standard'})” to cart`,
      'success'
    );
  };

  const handleAddAllFbtToCart = () => {
    if (!fbtData || !fbtData.items) return;
    const selectedItems = fbtData.items.filter((item: any) => selectedFbtIds.includes(item.id));
    if (selectedItems.length === 0) return;

    selectedItems.forEach((item: any) => {
      dispatch(
        addToCart({
          id: item.id,
          bookId: item.id,
          title: item.title,
          price: item.price,
          discountPrice: item.discountPrice ?? undefined,
          coverImage: item.coverImage ?? undefined,
          stock: 20,
          quantity: 1,
        })
      );
    });

    showToast(
      `Added ${selectedItems.length} complementary bundle books to cart! Combo discount applied.`,
      'success'
    );
  };

  if (loading) {
    return (
      <div className="mx-auto max-w-7xl animate-pulse px-4 py-16">
        <div className="h-[520px] rounded-3xl bg-zinc-200 dark:bg-zinc-800" />
      </div>
    );
  }

  if (!book) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-20 text-center">
        <AlertCircle className="mx-auto h-8 w-8 text-red-600" />
        <h1 className="mt-3 text-2xl font-extrabold">Product not found</h1>
        <p className="mt-2 text-sm text-zinc-500">{error}</p>
        <Link href="/books" className="mt-5 inline-block rounded-xl bg-[#701a08] px-5 py-3 text-xs font-bold text-white">
          Return to catalog
        </Link>
      </div>
    );
  }

  const specs = [
    ['Source product ID', book.sourceProductId],
    ['ISBN', currentIsbn],
    ['SKU', currentSku],
    ['Format', activeVariant ? activeVariant.format : (book.format || book.binding || 'Paperback')],
    ['Publisher', book.publisherName],
    ['Category', book.categoryName],
    ['Language', book.language],
    ['Edition', book.edition],
    ['Pages', book.pages],
    ['Publication year', book.publicationYear],
    ['Class', book.classGrade],
    ['Weight (kg)', activeVariant?.weight ?? book.weight],
    ['Dimensions', activeVariant?.dimensions ?? 'Standard Book Format'],
    ['GST', book.gstRate == null ? null : `${book.gstRate}%`],
  ].filter((item) => item[1] !== null && item[1] !== undefined && item[1] !== '');

  const formatIcons: Record<string, any> = {
    HARDCOVER: BookOpen,
    PAPERBACK: BookOpen,
    EBOOK: Tablet,
    AUDIOBOOK: Sparkles,
  };

  return (
    <div className="mx-auto max-w-7xl space-y-10 px-4 py-10 sm:px-6 lg:px-8">
      <nav className="flex items-center gap-2 text-xs font-semibold text-zinc-500">
        <Link href="/" className="hover:text-zinc-900 dark:hover:text-zinc-100">Home</Link>
        <span>/</span>
        <Link href="/books" className="hover:text-zinc-900 dark:hover:text-zinc-100">Catalog</Link>
        <span>/</span>
        <span className="line-clamp-1 text-zinc-900 dark:text-zinc-100">{book.title}</span>
      </nav>

      <div className="grid gap-10 lg:grid-cols-12">
        {/* Left Column: Gallery & Value Badges */}
        <section className="space-y-4 lg:col-span-5">
          <div className="flex min-h-[480px] items-center justify-center overflow-hidden rounded-3xl border border-zinc-200 bg-zinc-100 p-6 dark:border-zinc-800 dark:bg-zinc-900 shadow-sm">
            {selectedImage ? (
              <img src={selectedImage} alt={book.title} className="max-h-[480px] w-full object-contain transition-all duration-300" />
            ) : (
              <span className="text-sm text-zinc-400">Image unavailable</span>
            )}
          </div>
          {images.length > 1 && (
            <div className="flex gap-3 overflow-x-auto pb-2">
              {images.map((image) => (
                <button
                  key={image}
                  onClick={() => setSelectedImage(image)}
                  className={`h-20 w-16 shrink-0 overflow-hidden rounded-xl border-2 transition-all ${
                    selectedImage === image ? 'border-[#701a08] ring-2 ring-[#701a08]/20' : 'border-zinc-200 dark:border-zinc-800 opacity-70 hover:opacity-100'
                  }`}
                >
                  <img src={image} alt="" className="h-full w-full object-cover" />
                </button>
              ))}
            </div>
          )}
          <div className="grid grid-cols-3 gap-3 text-center text-[11px] font-bold">
            <div className="rounded-2xl border border-zinc-200 bg-zinc-50 p-3.5 dark:border-zinc-800 dark:bg-zinc-900/50">
              <Truck className="mx-auto mb-1.5 h-5 w-5 text-[#701a08]" />
              Worldwide delivery
            </div>
            <div className="rounded-2xl border border-zinc-200 bg-zinc-50 p-3.5 dark:border-zinc-800 dark:bg-zinc-900/50">
              <ShieldCheck className="mx-auto mb-1.5 h-5 w-5 text-emerald-600" />
              100% Authentic
            </div>
            <div className="rounded-2xl border border-zinc-200 bg-zinc-50 p-3.5 dark:border-zinc-800 dark:bg-zinc-900/50">
              <RotateCcw className="mx-auto mb-1.5 h-5 w-5 text-blue-600" />
              Easy Returns
            </div>
          </div>
        </section>

        {/* Right Column: Book Info, Variant Selector, Pricing, Add to Cart */}
        <section className="space-y-6 lg:col-span-7">
          <div>
            <div className="flex flex-wrap items-center gap-2 text-[10px] font-bold uppercase tracking-wider">
              <span className="rounded-md bg-amber-100 px-2.5 py-1 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300">
                {book.categoryName || 'General Books'}
              </span>
              <span
                className={`flex items-center gap-1 rounded-md px-2.5 py-1 ${
                  currentStock > 0
                    ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300'
                    : 'bg-rose-100 text-rose-800 dark:bg-rose-950/60 dark:text-rose-300'
                }`}
              >
                <CheckCircle2 className="h-3.5 w-3.5" />
                {isEbook ? 'Instant Digital Download' : currentStock > 0 ? `${currentStock} in stock` : 'Out of stock'}
              </span>
              {activeVariant && (
                <span className="rounded-md bg-zinc-100 px-2.5 py-1 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300">
                  SKU: {currentSku}
                </span>
              )}
            </div>

            <h1 className="mt-3 text-3xl sm:text-4xl font-extrabold leading-tight tracking-tight text-zinc-900 dark:text-zinc-50">
              {book.title}
            </h1>
            <p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
              By <strong className="text-[#701a08] font-bold dark:text-amber-500">{book.authorName || 'Indian Author'}</strong>
              {book.publisherName ? (
                <> · Published by <strong className="text-zinc-800 dark:text-zinc-200">{book.publisherName}</strong></>
              ) : null}
            </p>
          </div>

          {/* Book Format & Edition Variant Selector */}
          {book.variants && book.variants.length > 0 && (
            <div className="space-y-3 rounded-2xl border border-zinc-200/80 bg-zinc-50/70 p-5 dark:border-zinc-800 dark:bg-zinc-900/60">
              <div className="flex items-center justify-between">
                <label className="text-xs font-extrabold uppercase tracking-wider text-zinc-700 dark:text-zinc-300">
                  Select Format & Edition:
                </label>
                <span className="text-xs font-semibold text-zinc-500">
                  {book.variants.length} options available
                </span>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                {book.variants.map((v) => {
                  const Icon = formatIcons[v.format.toUpperCase()] || BookOpen;
                  const isSelected = selectedVariantId === v.id;
                  const vPrice = v.discountPrice || v.price;
                  return (
                    <button
                      key={v.id}
                      type="button"
                      onClick={() => {
                        setSelectedVariantId(v.id);
                        if (v.coverImage) setSelectedImage(v.coverImage);
                      }}
                      className={`relative flex flex-col items-start justify-between rounded-xl border p-4 text-left transition-all ${
                        isSelected
                          ? 'border-[#701a08] bg-white ring-2 ring-[#701a08]/20 dark:bg-zinc-800 dark:border-amber-600'
                          : 'border-zinc-200 bg-white/60 hover:border-zinc-400 dark:border-zinc-800 dark:bg-zinc-800/40'
                      }`}
                    >
                      <div className="flex w-full items-center justify-between">
                        <span className="flex items-center gap-1.5 text-xs font-extrabold uppercase tracking-wide text-zinc-900 dark:text-zinc-100">
                          <Icon className="h-4 w-4 text-[#701a08] dark:text-amber-500" />
                          {v.format}
                        </span>
                        {v.isDefault && (
                          <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[9px] font-extrabold text-amber-900 dark:bg-amber-900/60 dark:text-amber-200">
                            Popular
                          </span>
                        )}
                      </div>
                      <div className="mt-3">
                        <div className="text-lg font-black text-zinc-900 dark:text-zinc-50">
                          ₹{vPrice.toLocaleString('en-IN')}
                        </div>
                        {v.discountPrice && (
                          <div className="text-[11px] text-zinc-400 line-through">
                            ₹{v.price.toLocaleString('en-IN')}
                          </div>
                        )}
                      </div>
                      <div className="mt-2 text-[10px] font-semibold text-zinc-500 dark:text-zinc-400">
                        {v.format.toUpperCase() === 'EBOOK' ? (
                          <span className="text-blue-600 dark:text-blue-400 flex items-center gap-1">
                            <Zap className="h-3 w-3" /> Instant eBook
                          </span>
                        ) : v.stock > 0 ? (
                          `${v.stock} in stock`
                        ) : (
                          <span className="text-red-500">Out of stock</span>
                        )}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Pricing & Digital Delivery Callout */}
          <div className="rounded-2xl border border-zinc-200 bg-zinc-50 p-6 dark:border-zinc-800 dark:bg-zinc-900">
            <div className="flex items-baseline gap-3">
              <span className="text-3xl sm:text-4xl font-extrabold text-zinc-900 dark:text-zinc-50">
                ₹{currentSellingPrice.toLocaleString('en-IN')}
              </span>
              {currentDiscountPrice != null && (
                <span className="text-sm font-semibold text-zinc-400 line-through">
                  ₹{currentPrice.toLocaleString('en-IN')}
                </span>
              )}
              {currentDiscountPrice != null && (
                <span className="rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-black text-red-700 dark:bg-red-950/60 dark:text-red-300">
                  {Math.round(((currentPrice - currentDiscountPrice) / currentPrice) * 100)}% OFF
                </span>
              )}
            </div>
            {isEbook ? (
              <p className="mt-2 flex items-center gap-1.5 text-xs font-bold text-blue-700 dark:text-blue-400">
                <FileText className="h-4 w-4" /> Digital eBook edition — Instant PDF / EPUB download upon checkout.
              </p>
            ) : (
              <p className="mt-1 text-xs text-zinc-500">
                Taxes are applied according to statutory book publications GST (0%-5%). Free shipping on orders over ₹2,999.
              </p>
            )}
          </div>

          {/* Quantity and Actions */}
          <div className="flex flex-wrap items-center gap-4">
            {!isEbook && (
              <div className="flex items-center overflow-hidden rounded-xl border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-800">
                <button
                  type="button"
                  onClick={() => setQuantity(Math.max(1, quantity - 1))}
                  className="p-3 text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-700"
                >
                  <Minus className="h-4 w-4" />
                </button>
                <span className="min-w-10 text-center text-sm font-bold">{quantity}</span>
                <button
                  type="button"
                  onClick={() => setQuantity(Math.min(currentStock, quantity + 1))}
                  className="p-3 text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-700"
                >
                  <Plus className="h-4 w-4" />
                </button>
              </div>
            )}
            <button
              type="button"
              disabled={currentStock <= 0}
              onClick={addBookToCart}
              className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-[#701a08] px-6 py-3.5 text-sm font-extrabold text-white shadow-lg shadow-[#701a08]/20 transition-all hover:bg-[#851f0a] disabled:opacity-40"
            >
              <ShoppingBag className="h-4 w-4" />
              {isEbook ? 'Add eBook to cart' : 'Add to cart'}
            </button>
            <button
              type="button"
              disabled={currentStock <= 0}
              onClick={() => {
                addBookToCart();
                router.push('/checkout');
              }}
              className="rounded-xl border-2 border-[#701a08] px-6 py-3.5 text-sm font-extrabold text-[#701a08] hover:bg-[#701a08]/5 dark:border-amber-600 dark:text-amber-500 disabled:opacity-40"
            >
              Buy Now
            </button>
            <button
              type="button"
              disabled={wishlistLoading}
              onClick={handleToggleWishlist}
              className={`p-3.5 rounded-xl border-2 transition-all ${
                isInWishlist
                  ? 'border-rose-600 bg-rose-50 text-rose-600 dark:bg-rose-950/40 dark:border-rose-500'
                  : 'border-zinc-300 dark:border-zinc-700 text-zinc-600 dark:text-zinc-300 hover:border-rose-500 hover:text-rose-500'
              }`}
              title={isInWishlist ? 'Remove from Wishlist' : 'Add to Wishlist'}
            >
              <Heart className={`w-5 h-5 ${isInWishlist ? 'fill-rose-600 text-rose-600' : ''}`} />
            </button>
          </div>

          {/* Upselling Recommendation (Deluxe Hardcover / Commentary Upgrade) */}
          {upsells.length > 0 && (
            <div className="p-4 rounded-2xl bg-amber-500/10 dark:bg-amber-950/30 border border-amber-300 dark:border-amber-700/60 space-y-2">
              <div className="flex items-center justify-between">
                <span className="px-2.5 py-0.5 rounded-full bg-amber-600 text-white font-extrabold text-[10px] uppercase tracking-wider flex items-center gap-1">
                  <Sparkles className="w-3 h-3" /> {upsells[0].badge}
                </span>
                <span className="font-extrabold text-xs text-[#701a08] dark:text-amber-400">
                  {upsells[0].priceDifference}
                </span>
              </div>
              <p className="font-bold text-xs text-zinc-900 dark:text-zinc-100">{upsells[0].title}</p>
              <p className="text-[11px] text-zinc-600 dark:text-zinc-400 leading-relaxed">{upsells[0].reason}</p>
              {upsells[0].variantId && (
                <button
                  type="button"
                  onClick={() => setSelectedVariantId(upsells[0].variantId)}
                  className="px-3 py-1.5 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white text-xs font-bold shadow-sm transition-all flex items-center gap-1.5"
                >
                  <span>Switch to Deluxe Hardcover</span>
                  <ChevronRight className="w-3.5 h-3.5" />
                </button>
              )}
            </div>
          )}
        </section>
      </div>

      {/* Tabs Section */}
      <section className="rounded-3xl border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-900 shadow-sm overflow-hidden">
        <div className="flex flex-wrap gap-1 border-b border-zinc-200 p-3 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50">
          {(['description', 'specifications', 'variants', 'attributes', 'catalogues'] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`rounded-xl px-5 py-2.5 text-xs font-extrabold capitalize transition-all ${
                activeTab === tab
                  ? 'bg-[#701a08] text-white shadow-md'
                  : 'text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100'
              }`}
            >
              {tab === 'variants' ? `Editions (${book.variants?.length ?? 0})` : tab}
              {tab === 'attributes' ? ` (${book.attributes?.length ?? 0})` : ''}
              {tab === 'catalogues' ? ` (${book.catalogues?.length ?? 0})` : ''}
            </button>
          ))}
        </div>
        <div className="p-8 text-sm leading-relaxed text-zinc-700 dark:text-zinc-300">
          {activeTab === 'description' && (
            <>
              {book.descriptionHtml ? (
                <div className="prose max-w-none dark:prose-invert" dangerouslySetInnerHTML={{ __html: book.descriptionHtml }} />
              ) : (
                <p className="whitespace-pre-line">{book.description || 'No description supplied.'}</p>
              )}
              {book.additionalAttributesHtml && (
                <div className="prose mt-6 max-w-none dark:prose-invert" dangerouslySetInnerHTML={{ __html: book.additionalAttributesHtml }} />
              )}
            </>
          )}

          {activeTab === 'specifications' && (
            <dl className="grid gap-x-10 gap-y-4 md:grid-cols-2">
              {specs.map(([label, value]) => (
                <div key={String(label)} className="flex justify-between gap-4 border-b border-zinc-100 py-2.5 dark:border-zinc-800">
                  <dt className="font-bold text-zinc-500 dark:text-zinc-400">{label}</dt>
                  <dd className="text-right font-bold text-zinc-900 dark:text-zinc-100">{String(value)}</dd>
                </div>
              ))}
            </dl>
          )}

          {activeTab === 'variants' && (
            <div className="space-y-4">
              <h3 className="text-base font-extrabold text-zinc-900 dark:text-zinc-100">All Available Formats & Editions</h3>
              {book.variants && book.variants.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="border-b border-zinc-200 font-extrabold text-zinc-500 dark:border-zinc-800">
                      <tr>
                        <th className="pb-3">Format</th>
                        <th className="pb-3">SKU</th>
                        <th className="pb-3">ISBN</th>
                        <th className="pb-3">Stock</th>
                        <th className="pb-3">Price</th>
                        <th className="pb-3 text-right">Action</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                      {book.variants.map((v) => (
                        <tr key={v.id} className="hover:bg-zinc-50/50 dark:hover:bg-zinc-800/50">
                          <td className="py-3 font-bold uppercase">{v.format}</td>
                          <td className="py-3 font-mono text-zinc-500">{v.sku}</td>
                          <td className="py-3 font-mono text-zinc-500">{v.isbn || 'N/A'}</td>
                          <td className="py-3 font-semibold">
                            {v.format.toUpperCase() === 'EBOOK' ? 'Unlimited (Digital)' : `${v.stock} units`}
                          </td>
                          <td className="py-3 font-bold text-[#701a08] dark:text-amber-500">
                            ₹{(v.discountPrice || v.price).toLocaleString('en-IN')}
                          </td>
                          <td className="py-3 text-right">
                            <button
                              type="button"
                              onClick={() => {
                                setSelectedVariantId(v.id);
                                window.scrollTo({ top: 100, behavior: 'smooth' });
                              }}
                              className="rounded-lg bg-zinc-100 px-3 py-1 text-[11px] font-bold text-zinc-800 hover:bg-[#701a08] hover:text-white dark:bg-zinc-800 dark:text-zinc-200"
                            >
                              Select Edition
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="text-zinc-500">Single edition product.</p>
              )}
            </div>
          )}

          {activeTab === 'attributes' && (
            book.attributes?.length ? (
              <dl className="grid gap-x-10 gap-y-4 md:grid-cols-2">
                {book.attributes.map((attribute) => (
                  <div key={attribute.id} className="flex justify-between gap-4 border-b border-zinc-100 py-2.5 dark:border-zinc-800">
                    <dt className="font-bold text-zinc-500">{attribute.name}</dt>
                    <dd className="text-right font-medium">{attribute.value}</dd>
                  </div>
                ))}
              </dl>
            ) : (
              <p className="text-zinc-500">No custom attributes supplied.</p>
            )
          )}

          {activeTab === 'catalogues' && (
            book.catalogues?.length ? (
              <div className="grid gap-4 md:grid-cols-2">
                {book.catalogues.map((catalogue) => (
                  <a
                    key={catalogue.id}
                    href={catalogue.pdfUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="flex items-center justify-between rounded-2xl border border-zinc-200 p-5 font-bold text-[#701a08] hover:border-[#701a08] dark:border-zinc-800 dark:text-amber-500"
                  >
                    <span>{catalogue.title}</span>
                    <Download className="h-5 w-5" />
                  </a>
                ))}
              </div>
            ) : (
              <p className="text-zinc-500">No explicit product-to-catalogue PDF link is present.</p>
            )
          )}
        </div>
      </section>

      {/* Frequently Bought Together (Smart Sales Combo) */}
      {fbtData && fbtData.items && fbtData.items.length > 1 && (
        <section className="rounded-3xl border border-zinc-200 bg-white p-6 sm:p-8 dark:border-zinc-800 dark:bg-zinc-900 shadow-sm space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-zinc-100 dark:border-zinc-800 pb-4">
            <div>
              <span className="px-3 py-1 rounded-full bg-emerald-50 dark:bg-emerald-950/50 text-emerald-700 dark:text-emerald-400 font-extrabold text-[11px] uppercase tracking-wider">
                Smart Combo Offer
              </span>
              <h3 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-100 mt-1">
                Frequently Bought Together
              </h3>
            </div>
            <span className="text-xs font-bold text-[#701a08] dark:text-amber-400">
              {fbtData.badgeText}
            </span>
          </div>

          <div className="flex flex-col lg:flex-row items-center gap-6">
            {/* Visual Book Covers Linked with '+' */}
            <div className="flex flex-wrap items-center justify-center gap-3">
              {fbtData.items.map((item: any, idx: number) => {
                const isChecked = selectedFbtIds.includes(item.id);
                return (
                  <React.Fragment key={item.id}>
                    {idx > 0 && <span className="text-2xl font-bold text-zinc-300 dark:text-zinc-600">+</span>}
                    <div
                      onClick={() => {
                        setSelectedFbtIds((prev) =>
                          prev.includes(item.id)
                            ? prev.filter((id) => id !== item.id)
                            : [...prev, item.id]
                        );
                      }}
                      className={`relative p-3 rounded-2xl border-2 transition-all cursor-pointer w-28 sm:w-32 text-center space-y-2 ${
                        isChecked
                          ? 'border-[#701a08] dark:border-amber-500 bg-amber-500/5'
                          : 'border-zinc-200 dark:border-zinc-800 opacity-40'
                      }`}
                    >
                      <div className="w-full h-32 rounded-xl bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center overflow-hidden">
                        {item.coverImage ? (
                          <img src={item.coverImage} alt={item.title} className="w-full h-full object-cover" />
                        ) : (
                          <span className="text-[10px] text-zinc-400">Book</span>
                        )}
                      </div>
                      <p className="text-[10px] font-bold text-zinc-900 dark:text-zinc-100 line-clamp-2">
                        {item.title}
                      </p>
                      <span className="text-xs font-black text-[#701a08] dark:text-amber-400 block">
                        ₹{item.effectivePrice}
                      </span>
                    </div>
                  </React.Fragment>
                );
              })}
            </div>

            {/* Checkbox List & Combined CTA Action */}
            <div className="flex-1 w-full lg:w-auto p-6 rounded-2xl bg-zinc-50 dark:bg-zinc-800/40 border border-zinc-200 dark:border-zinc-700/60 space-y-4 text-xs">
              <div className="space-y-2">
                {fbtData.items.map((item: any) => {
                  const isChecked = selectedFbtIds.includes(item.id);
                  return (
                    <label key={item.id} className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={isChecked}
                        onChange={() => {
                          setSelectedFbtIds((prev) =>
                            prev.includes(item.id)
                              ? prev.filter((id) => id !== item.id)
                              : [...prev, item.id]
                          );
                        }}
                        className="rounded border-zinc-300 text-[#701a08] focus:ring-[#701a08]"
                      />
                      <span className="font-medium flex-1 line-clamp-1">
                        <span className="font-bold">{item.isPrimary ? 'This item: ' : ''}</span>
                        {item.title}
                      </span>
                      <span className="font-black text-[#701a08] dark:text-amber-400">
                        ₹{item.effectivePrice}
                      </span>
                    </label>
                  );
                })}
              </div>

              <div className="pt-3 border-t border-zinc-200 dark:border-zinc-700 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div>
                  <span className="text-zinc-500 text-[11px]">Bundle Price for {selectedFbtIds.length} Selected Books:</span>
                  <div className="flex items-baseline gap-2">
                    <span className="text-xl font-extrabold text-[#701a08] dark:text-amber-400">
                      ₹
                      {Math.round(
                        fbtData.items
                          .filter((i: any) => selectedFbtIds.includes(i.id))
                          .reduce((sum: number, i: any) => sum + i.effectivePrice, 0) *
                          (selectedFbtIds.length >= 3 ? 0.88 : 1)
                      )}
                    </span>
                    {selectedFbtIds.length >= 3 && (
                      <span className="text-xs font-bold text-emerald-600 bg-emerald-50 dark:bg-emerald-950/60 px-2 py-0.5 rounded-md">
                        12% Combo Savings Applied
                      </span>
                    )}
                  </div>
                </div>

                <button
                  type="button"
                  disabled={selectedFbtIds.length === 0}
                  onClick={handleAddAllFbtToCart}
                  className="w-full sm:w-auto px-6 py-3 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white font-extrabold text-xs shadow-md transition-all disabled:opacity-40 cursor-pointer flex items-center justify-center gap-2"
                >
                  <ShoppingBag className="w-4 h-4" />
                  <span>Add Selected ({selectedFbtIds.length}) to Cart</span>
                </button>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Recently Viewed Books Section */}
      {otherRecentlyViewed && otherRecentlyViewed.length > 0 && (
        <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 mt-12">
          <div className="flex items-center justify-between border-b border-zinc-200 dark:border-zinc-800 pb-4">
            <div>
              <h3 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
                <Clock className="w-5 h-5 text-saffron-500" /> Recently Viewed Books
              </h3>
              <p className="text-xs text-zinc-500 mt-0.5">Jump back to your recently viewed books</p>
            </div>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            {otherRecentlyViewed.map((b) => (
              <div
                key={b.id}
                className="bg-white dark:bg-zinc-900 p-4 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm hover:shadow-lg transition-all flex flex-col justify-between group"
              >
                <Link href={`/books/${b.slug}`} className="block flex-1">
                  <div className="w-full aspect-[3/4] rounded-2xl overflow-hidden bg-zinc-100 dark:bg-zinc-800 relative">
                    <img
                      src={bookCoverUrl(b.coverImage)}
                      alt={b.title}
                      className="w-full h-full object-cover group-hover:scale-102 transition-transform"
                    />
                  </div>

                  <div className="pt-4 space-y-1.5">
                    <span className="text-[10px] text-zinc-400 font-bold uppercase tracking-wider block">{b.categoryName}</span>
                    <h4 className="font-extrabold text-xs text-zinc-950 dark:text-zinc-100 line-clamp-2 mt-0.5 group-hover:text-[#701a08] transition-colors">{b.title}</h4>
                    <span className="text-[10px] text-zinc-550 block mt-0.5">{b.authorName}</span>
                  </div>
                </Link>

                <div className="pt-2 flex items-center justify-between border-t border-zinc-100 dark:border-zinc-800 mt-2">
                  <div className="flex flex-col">
                    {b.discountPrice ? (
                      <>
                        <span className="text-xs font-bold text-zinc-400 line-through">₹{b.price}</span>
                        <span className="text-sm font-extrabold text-[#701a08]">₹{b.discountPrice}</span>
                      </>
                    ) : (
                      <span className="text-sm font-extrabold text-[#701a08]">₹{b.price}</span>
                    )}
                  </div>

                  <button
                    onClick={() => {
                      dispatch(
                        addToCart({
                          id: b.id,
                          bookId: b.id,
                          title: b.title,
                          price: b.price,
                          discountPrice: b.discountPrice ?? undefined,
                          coverImage: b.coverImage ?? undefined,
                          stock: b.stock,
                        })
                      );
                      showToast('Added to cart!');
                    }}
                    className="px-3 py-2 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white font-extrabold text-[10px] shadow-sm transition-colors"
                  >
                    Add
                  </button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
