import { Head, Link, router } from '@inertiajs/react';
import { Check, ChevronDown, Heart, Minus, Plus, Ruler, ShieldCheck, ShoppingBag, ShoppingCart, Sparkles, Star, Truck } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';

import FabricPreviewModal from '@/components/fabric-preview-modal';
import FrontendLayout from '@/layouts/frontend-layout';
import { useLang } from '@/lib/lang';
import { xsrfToken } from '@/lib/utils';
import { type Product, type ProductVariant } from '@/types';

const COLOR_HEX: Record<string, string> = {
    amber: '#D97706',
    black: '#111827',
    blue: '#2A3E55',
    brown: '#7C4A2D',
    charcoal: '#2B3640',
    cream: '#EAE0CB',
    gold: '#B8893F',
    gray: '#9CA3AF',
    green: '#4A7A4A',
    grey: '#9CA3AF',
    ivory: '#FBF7EF',
    maroon: '#6B2E2E',
    navy: '#2A3E55',
    olive: '#8C8042',
    red: '#8E3B2E',
    slate: '#2B3640',
    teal: '#0D9488',
    white: '#F9FAFB',
};

const isColorAttr = (name: string) => /color|colour|rang/i.test(name);

interface AttrGroup {
    name: string;
    values: string[];
}

type GarmentType = 'Punjabi' | 'Shirt' | 'Kabli';

const usageOptions: Array<{
    type: GarmentType;
    length: string;
    suggestion: string;
    cuts: string[];
}> = [
    {
        type: 'Punjabi',
        length: '3.5-4 yd',
        suggestion: 'Best for a clean traditional Punjabi with a band or simple collar.',
        cuts: ['Band collar', 'Mandarin', 'Simple cuff'],
    },
    {
        type: 'Shirt',
        length: '2.5-3 yd',
        suggestion: 'Suitable for a refined casual shirt with full or half sleeves.',
        cuts: ['Full sleeve', 'Half sleeve', 'Soft drape'],
    },
    {
        type: 'Kabli',
        length: '4-5+ yd',
        suggestion: 'Ideal for a traditional Kabli set depending on tailor design.',
        cuts: ['Tunic length', 'Trouser set', 'Minimal trim'],
    },
];

const lengthOptions = ['2.5 yd', '3 yd', '3.5 yd', '4 yd', '5 yd', 'Custom'];

function buildAttrGroups(variants: ProductVariant[]): AttrGroup[] {
    const map = new Map<string, Set<string>>();
    variants.forEach((variant) => {
        if (variant.attribute_values?.length) {
            variant.attribute_values.forEach((value) => {
                const attr = value.attribute?.name ?? 'Variant';
                if (!map.has(attr)) map.set(attr, new Set());
                map.get(attr)!.add(value.value);
            });
        } else {
            if (!map.has('Variant')) map.set('Variant', new Set());
            map.get('Variant')!.add(variant.variant_name);
        }
    });

    return Array.from(map.entries()).map(([name, values]) => ({ name, values: Array.from(values) }));
}

function findVariant(selection: Record<string, string>, variants: ProductVariant[]): ProductVariant | null {
    const selectedValues = Object.values(selection);
    if (!selectedValues.length) return null;

    return (
        variants.find((variant) => {
            const variantValues = variant.attribute_values?.length ? variant.attribute_values.map((value) => value.value) : [variant.variant_name];

            return selectedValues.every((value) => variantValues.includes(value));
        }) ?? null
    );
}

function isAvailable(attrName: string, value: string, selection: Record<string, string>, variants: ProductVariant[]): boolean {
    const testSelection = { ...selection, [attrName]: value };
    const selectedValues = Object.values(testSelection);

    return variants.some((variant) => {
        const variantValues = variant.attribute_values?.length
            ? variant.attribute_values.map((attrValue) => attrValue.value)
            : [variant.variant_name];

        return selectedValues.every((selected) => variantValues.includes(selected));
    });
}

function colorForValue(value?: string | null): string {
    if (!value) return '#8C8042';
    const normalized = value.toLowerCase();
    const direct = COLOR_HEX[normalized];
    if (direct) return direct;

    const match = Object.entries(COLOR_HEX).find(([name]) => normalized.includes(name));
    return match?.[1] ?? '#8C8042';
}

function DiamondGlyph({ className = 'h-5 w-5' }: { className?: string }) {
    return (
        <svg viewBox="0 0 40 40" fill="none" className={className} aria-hidden="true">
            <path d="M20 2 38 20 20 38 2 20 20 2Z" stroke="currentColor" strokeWidth="1.2" />
            <path d="M20 10 30 20 20 30 10 20 20 10Z" stroke="currentColor" strokeWidth="1.2" />
            <path d="M17 17v6M23 17v6M17 20h6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
        </svg>
    );
}

function FabricTexture({ color, label, className = '' }: { color: string; label?: string; className?: string }) {
    return (
        <div
            className={`relative overflow-hidden ${className}`}
            style={{
                backgroundColor: color,
                backgroundImage:
                    'repeating-linear-gradient(45deg, rgba(0,0,0,.08) 0 2px, transparent 2px 7px), repeating-linear-gradient(-45deg, rgba(255,255,255,.08) 0 2px, transparent 2px 7px)',
            }}
        >
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 via-transparent to-black/20" />
            {label && <span className="absolute top-3 left-3 font-mono text-[10px] tracking-[0.18em] text-white/75 uppercase">{label}</span>}
            <span className="absolute right-3 bottom-3 font-mono text-[10px] text-white/45">diamond weave</span>
        </div>
    );
}

function GarmentSilhouette({ kind, color, className = '' }: { kind: GarmentType; color: string; className?: string }) {
    const accent = 'rgba(0,0,0,.22)';
    const figure = 'rgba(43,54,64,.18)';

    return (
        <svg viewBox="0 0 200 240" preserveAspectRatio="xMidYMid meet" className={`block h-full w-full ${className}`} aria-hidden="true">
            <ellipse cx="100" cy="230" rx="48" ry="4" fill="rgba(0,0,0,.10)" />
            <circle cx="100" cy="34" r="14" fill={figure} />
            <path d="M92 46v10q8 6 16 0V46Z" fill={figure} />

            {kind === 'Punjabi' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v130H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 76l-4 54 14 2V90Z" fill={color} />
                    <path d="M130 60 148 76l4 54-14 2V90Z" fill={color} />
                    <path d="M88 56q12 8 24 0v-7q-12 5-24 0Z" fill={accent} opacity=".65" />
                    <line x1="100" y1="62" x2="100" y2="142" stroke={accent} strokeWidth="1.3" />
                    {[78, 94, 110, 126, 142].map((y) => (
                        <circle key={y} cx="100" cy={y} r="1.7" fill="rgba(0,0,0,.48)" />
                    ))}
                    <rect x="62" y="210" width="76" height="10" fill="rgba(0,0,0,.10)" />
                </g>
            )}

            {kind === 'Shirt' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v80H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 80l-4 70 14 2V90Z" fill={color} />
                    <path d="M130 60 148 80l4 70-14 2V90Z" fill={color} />
                    <path d="M88 56 100 77l12-21v-7q-12 5-24 0Z" fill={accent} opacity=".65" />
                    <line x1="100" y1="78" x2="100" y2="160" stroke={accent} strokeWidth="1.3" />
                    <rect x="76" y="94" width="15" height="15" fill={accent} opacity=".35" />
                    <rect x="62" y="162" width="76" height="8" fill="rgba(0,0,0,.10)" />
                </g>
            )}

            {kind === 'Kabli' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v90H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 78l-4 62 14 4V90Z" fill={color} />
                    <path d="M130 60 148 78l4 62-14 4V90Z" fill={color} />
                    <path d="M90 56 100 65l10-9v-8q-10 5-20 0Z" fill={accent} opacity=".7" />
                    <path d="M100 65 122 90v70h-22Z" fill="rgba(0,0,0,.06)" />
                    <line x1="100" y1="65" x2="122" y2="90" stroke={accent} strokeWidth="1.3" />
                    <path d="M70 180v50h26l4-46 4 46h26v-50Z" fill={color} opacity=".96" />
                    <line x1="100" y1="184" x2="100" y2="230" stroke={accent} strokeWidth="1" />
                </g>
            )}

            <g opacity=".17" stroke="rgba(255,255,255,.65)" strokeWidth=".5">
                <line x1="62" y1="100" x2="138" y2="100" />
                <line x1="62" y1="122" x2="138" y2="122" />
                <line x1="62" y1="144" x2="138" y2="144" />
                <line x1="62" y1="166" x2="138" y2="166" />
            </g>
        </svg>
    );
}

function ProductGallery({
    product,
    variantImage,
    fabricColor,
    onPreviewTypeChange,
}: {
    product: Product;
    variantImage?: string | null;
    fabricColor: string;
    onPreviewTypeChange: (type: GarmentType) => void;
}) {
    const { t } = useLang();
    const images = product.images ?? [];
    const primary = images.find((image) => image.is_primary) ?? images[0];
    const [active, setActive] = useState<string | null>(primary?.image ?? null);
    const [galleryMode, setGalleryMode] = useState<'photo' | 'fabric' | GarmentType>('photo');

    useEffect(() => {
        if (variantImage) {
            setActive(variantImage);
            setGalleryMode('photo');
        } else if (primary?.image) {
            setActive(primary.image);
        }
    }, [variantImage, primary?.image]);

    const showPhoto = galleryMode === 'photo' && active;

    return (
        <div className="grid gap-3 lg:grid-cols-[84px_1fr]">
            <div className="order-2 flex gap-2 overflow-x-auto pb-1 lg:order-1 lg:flex-col lg:overflow-visible lg:pb-0">
                {images.slice(0, 5).map((image) => (
                    <button
                        key={image.id}
                        onClick={() => {
                            setActive(image.image);
                            setGalleryMode('photo');
                        }}
                        className={`h-20 w-20 shrink-0 overflow-hidden border bg-white transition ${
                            galleryMode === 'photo' && active === image.image
                                ? 'border-[var(--brand-gold)]'
                                : 'border-[var(--brand-line)] hover:border-[var(--brand-gold)]'
                        }`}
                    >
                        <img src={`/storage/${image.image}`} alt="" className="h-full w-full object-cover" />
                    </button>
                ))}

                <button
                    onClick={() => setGalleryMode('fabric')}
                    className={`h-20 w-20 shrink-0 overflow-hidden border transition ${
                        galleryMode === 'fabric' ? 'border-[var(--brand-gold)]' : 'border-[var(--brand-line)] hover:border-[var(--brand-gold)]'
                    }`}
                >
                    <FabricTexture color={fabricColor} label="weave" className="h-full w-full" />
                </button>

                {usageOptions.map((option) => (
                    <button
                        key={option.type}
                        onClick={() => {
                            setGalleryMode(option.type);
                            onPreviewTypeChange(option.type);
                        }}
                        className={`h-20 w-20 shrink-0 border bg-[var(--brand-ivory)] transition ${
                            galleryMode === option.type ? 'border-[var(--brand-gold)]' : 'border-[var(--brand-line)] hover:border-[var(--brand-gold)]'
                        }`}
                        title={`Preview as ${option.type}`}
                    >
                        <GarmentSilhouette kind={option.type} color={fabricColor} />
                    </button>
                ))}
            </div>

            <div className="order-1 overflow-hidden border border-[var(--brand-line)] bg-[var(--brand-ivory)] lg:order-2">
                <div className="relative aspect-[4/5]">
                    {showPhoto ? (
                        <img src={`/storage/${active}`} alt={product.name} className="h-full w-full object-contain p-5" />
                    ) : galleryMode === 'fabric' ? (
                        <FabricTexture color={fabricColor} label="fabric close-up" className="h-full w-full" />
                    ) : (
                        <div className="ornament-bg flex h-full items-center justify-center bg-[var(--brand-cream)]">
                            <div className="h-[86%] w-[72%]">
                                <GarmentSilhouette kind={galleryMode as GarmentType} color={fabricColor} />
                            </div>
                        </div>
                    )}

                    {!images.length && galleryMode === 'photo' && (
                        <div className="flex h-full items-center justify-center bg-[var(--brand-cream)] text-center text-[var(--brand-muted)]">
                            <div>
                                <ShoppingBag size={42} className="mx-auto mb-3 opacity-35" />
                                <p className="text-sm">{t.productShow.noImage}</p>
                            </div>
                        </div>
                    )}

                    <div className="absolute top-4 left-4 flex items-center gap-2 bg-[var(--brand-slate)] px-3 py-2 text-[var(--brand-ivory)] shadow-lg">
                        <DiamondGlyph className="h-4 w-4 text-[var(--brand-gold)]" />
                        <span className="eyebrow text-[10px]">Fabric preview</span>
                    </div>
                </div>
            </div>
        </div>
    );
}

function AttrSelector({
    groups,
    selections,
    onSelect,
    variants,
}: {
    groups: AttrGroup[];
    selections: Record<string, string>;
    onSelect: (attr: string, value: string) => void;
    variants: ProductVariant[];
}) {
    if (!groups.length) return null;

    return (
        <div className="space-y-5">
            {groups.map((group) => {
                const selected = selections[group.name];
                const isColor = isColorAttr(group.name);

                return (
                    <div key={group.name}>
                        <div className="mb-3 flex items-center justify-between gap-3">
                            <span className="eyebrow text-[var(--brand-muted)]">{group.name}</span>
                            {selected && <span className="text-xs text-[var(--brand-gold-dim)]">{selected}</span>}
                        </div>

                        <div className="flex flex-wrap gap-2">
                            {group.values.map((value) => {
                                const selectedValue = selected === value;
                                const available = isAvailable(group.name, value, selections, variants);
                                const color = isColor ? colorForValue(value) : null;

                                if (isColor && color) {
                                    return (
                                        <button
                                            key={value}
                                            title={value}
                                            onClick={() => available && onSelect(group.name, value)}
                                            disabled={!available}
                                            className={`relative h-10 w-10 rounded-full border transition ${
                                                selectedValue
                                                    ? 'border-[var(--brand-slate)] ring-2 ring-[var(--brand-gold)] ring-offset-2'
                                                    : 'border-[var(--brand-line)] hover:border-[var(--brand-gold)]'
                                            } ${available ? '' : 'cursor-not-allowed opacity-35'}`}
                                            style={{ backgroundColor: color }}
                                        >
                                            {selectedValue && <Check size={14} className="absolute inset-0 m-auto text-white drop-shadow" />}
                                        </button>
                                    );
                                }

                                return (
                                    <button
                                        key={value}
                                        onClick={() => available && onSelect(group.name, value)}
                                        disabled={!available}
                                        className={`border px-4 py-2 text-sm transition ${
                                            !available
                                                ? 'cursor-not-allowed border-[var(--brand-line)] bg-white/40 text-[var(--brand-muted)] line-through opacity-50'
                                                : selectedValue
                                                  ? 'border-[var(--brand-slate)] bg-[var(--brand-slate)] text-[var(--brand-ivory)]'
                                                  : 'border-[var(--brand-line)] bg-white text-[var(--brand-ink)] hover:border-[var(--brand-gold)]'
                                        }`}
                                    >
                                        {value}
                                    </button>
                                );
                            })}
                        </div>
                    </div>
                );
            })}
        </div>
    );
}

function UsageSelector({ selected, onSelect, fabricColor }: { selected: GarmentType; onSelect: (type: GarmentType) => void; fabricColor: string }) {
    return (
        <div className="space-y-3">
            <div className="eyebrow text-[var(--brand-muted)]">Choose intended use</div>
            <div className="grid gap-3 sm:grid-cols-3">
                {usageOptions.map((option) => (
                    <button
                        key={option.type}
                        onClick={() => onSelect(option.type)}
                        className={`border p-3 text-left transition ${
                            selected === option.type
                                ? 'border-[var(--brand-gold)] bg-[var(--brand-ivory)] shadow-[0_18px_40px_-30px_rgba(0,0,0,.4)]'
                                : 'border-[var(--brand-line)] bg-white hover:border-[var(--brand-gold)]'
                        }`}
                    >
                        <div className="mx-auto mb-2 h-24 max-w-[86px]">
                            <GarmentSilhouette kind={option.type} color={fabricColor} />
                        </div>
                        <div className="font-display text-xl text-[var(--brand-ink)]">{option.type}</div>
                        <div className="mt-1 text-xs font-medium text-[var(--brand-gold-dim)]">{option.length}</div>
                    </button>
                ))}
            </div>
        </div>
    );
}

function PreviewPanel({ selected, fabricColor }: { selected: GarmentType; fabricColor: string }) {
    const option = usageOptions.find((item) => item.type === selected)!;

    return (
        <section className="grid gap-5 border border-[var(--brand-line)] bg-[var(--brand-slate)] p-5 text-[var(--brand-ivory)] md:grid-cols-[minmax(220px,0.85fr)_1fr]">
            <div className="ornament-bg flex min-h-[300px] items-center justify-center bg-[#20292f]">
                <div className="h-[280px] w-[220px]">
                    <GarmentSilhouette kind={selected} color={fabricColor} />
                </div>
            </div>
            <div className="flex flex-col justify-center">
                <div className="eyebrow mb-3 text-[var(--brand-gold)]">How this fabric may look</div>
                <h2 className="font-display text-4xl leading-tight md:text-5xl">As {selected}</h2>
                <p className="mt-4 max-w-xl text-sm leading-7 text-white/70">{option.suggestion}</p>
                <div className="mt-6 grid gap-3 sm:grid-cols-3">
                    {option.cuts.map((cut) => (
                        <div key={cut} className="border border-white/10 bg-white/[0.03] px-3 py-3 text-sm">
                            {cut}
                        </div>
                    ))}
                </div>
                <p className="mt-5 text-xs leading-6 text-white/45">
                    Preview is an illustration to help judge colour and drape. Final look depends on tailor pattern, lighting, and fabric batch.
                </p>
            </div>
        </section>
    );
}

function AccordionItem({ title, children, defaultOpen = false }: { title: string; children: React.ReactNode; defaultOpen?: boolean }) {
    const [open, setOpen] = useState(defaultOpen);

    return (
        <div className="border-b border-[var(--brand-line)]">
            <button onClick={() => setOpen((value) => !value)} className="flex w-full items-center justify-between gap-4 py-5 text-left">
                <span className="font-display text-2xl text-[var(--brand-ink)]">{title}</span>
                <ChevronDown size={18} className={`text-[var(--brand-gold)] transition ${open ? 'rotate-180' : ''}`} />
            </button>
            {open && <div className="pb-6 text-sm leading-7 text-[var(--brand-muted)]">{children}</div>}
        </div>
    );
}

function RelatedCard({ product }: { product: Product }) {
    const image = product.images?.find((item) => item.is_primary) ?? product.images?.[0];
    const discounted = product.compare_price && Number(product.compare_price) > Number(product.price);

    return (
        <Link href={`/products/${product.slug}`} className="group block">
            <div className="overflow-hidden border border-[var(--brand-line)] bg-[var(--brand-ivory)]">
                <div className="aspect-[4/5] overflow-hidden bg-[var(--brand-cream)]">
                    {image ? (
                        <img
                            src={`/storage/${image.image}`}
                            alt={product.name}
                            className="h-full w-full object-cover transition duration-500 group-hover:scale-105"
                        />
                    ) : (
                        <FabricTexture color={colorForValue(product.name)} label="fabric" className="h-full w-full" />
                    )}
                </div>
            </div>
            <div className="mt-3">
                <p className="line-clamp-2 text-sm text-[var(--brand-ink)] transition group-hover:text-[var(--brand-gold-dim)]">{product.name}</p>
                <div className="mt-1 flex items-center gap-2">
                    <span className="font-display text-xl text-[var(--brand-ink)]">Tk {Number(product.price).toLocaleString()}</span>
                    {discounted && (
                        <span className="text-xs text-[var(--brand-muted)] line-through">Tk {Number(product.compare_price).toLocaleString()}</span>
                    )}
                </div>
            </div>
        </Link>
    );
}

export default function ProductShow({ product, relatedProducts }: { product: Product; relatedProducts: Product[] }) {
    const { t } = useLang();
    const [qty, setQty] = useState(1);
    const [selectedAttrs, setSelectedAttrs] = useState<Record<string, string>>({});
    const [adding, setAdding] = useState(false);
    const [added, setAdded] = useState(false);
    const [variantError, setVariantError] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [usage, setUsage] = useState<GarmentType>('Punjabi');
    const [length, setLength] = useState('3.5 yd');

    const variants = useMemo(() => product.variants ?? [], [product.variants]);
    const attrGroups = useMemo(() => buildAttrGroups(variants), [variants]);
    const selectedVariant = useMemo(() => (attrGroups.length ? findVariant(selectedAttrs, variants) : null), [selectedAttrs, variants, attrGroups]);

    const hasVariants = attrGroups.length > 0;
    const allAttrsSelected = !hasVariants || Object.keys(selectedAttrs).length === attrGroups.length;
    const effectivePrice = selectedVariant ? Number(selectedVariant.price) : Number(product.price);
    const hasDiscount = product.compare_price && Number(product.compare_price) > Number(product.price);
    const discountPct = hasDiscount ? Math.round(((Number(product.compare_price) - Number(product.price)) / Number(product.compare_price)) * 100) : 0;
    const stockQty = selectedVariant ? selectedVariant.stock_qty : product.stock_qty;
    const inStock = (stockQty ?? 0) > 0;
    const colorAttr = attrGroups.find((group) => isColorAttr(group.name));
    const selectedColorName = colorAttr ? selectedAttrs[colorAttr.name] : product.name;
    const fabricColor = colorForValue(selectedColorName);
    const variantImage = selectedVariant && 'image' in selectedVariant ? (selectedVariant.image as string | null) : null;

    const handleAttrSelect = (attr: string, value: string) => {
        setSelectedAttrs((previous) => {
            if (previous[attr] === value) {
                const next = { ...previous };
                delete next[attr];
                return next;
            }

            return { ...previous, [attr]: value };
        });
        setVariantError(false);
    };

    const addToCart = async () => {
        if (adding || !inStock) return;
        if (hasVariants && !allAttrsSelected) {
            setVariantError(true);
            return;
        }

        setAdding(true);
        try {
            const response = await fetch('/cart/add', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': xsrfToken(),
                },
                body: JSON.stringify({
                    product_id: product.id,
                    variant_id: selectedVariant?.id ?? null,
                    qty,
                    usage,
                    length,
                }),
            });

            if (response.ok) {
                setAdded(true);
                router.reload({ preserveScroll: true });
                setTimeout(() => setAdded(false), 2500);
            }
        } finally {
            setAdding(false);
        }
    };

    return (
        <>
            <FrontendLayout>
                <Head title={product.name} />

                <div className="bg-[var(--brand-cream)] text-[var(--brand-ink)]">
                    <div className="mx-auto max-w-[1500px] px-4 py-6 sm:px-6 lg:px-10 lg:py-10">
                        <nav className="mb-7 flex flex-wrap items-center gap-2 text-xs text-[var(--brand-muted)]">
                            <Link href="/" className="link-gold hover:text-[var(--brand-gold-dim)]">
                                {t.productShow.home}
                            </Link>
                            <span>/</span>
                            <Link href="/products" className="link-gold hover:text-[var(--brand-gold-dim)]">
                                Fabrics
                            </Link>
                            {product.category && (
                                <>
                                    <span>/</span>
                                    <Link
                                        href={`/products?category=${product.category.slug}`}
                                        className="link-gold hover:text-[var(--brand-gold-dim)]"
                                    >
                                        {product.category.name}
                                    </Link>
                                </>
                            )}
                            <span>/</span>
                            <span className="line-clamp-1 text-[var(--brand-ink)]">{product.name}</span>
                        </nav>

                        <div className="grid gap-10 lg:grid-cols-[minmax(0,1.05fr)_minmax(420px,.95fr)] xl:gap-14">
                            <div className="lg:sticky lg:top-28 lg:self-start">
                                <ProductGallery
                                    product={product}
                                    variantImage={variantImage}
                                    fabricColor={fabricColor}
                                    onPreviewTypeChange={setUsage}
                                />
                            </div>

                            <aside className="border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-5 shadow-[0_30px_80px_-60px_rgba(0,0,0,.45)] md:p-7">
                                <div className="mb-4 flex flex-wrap items-center gap-2">
                                    {(product.brand || product.category) && (
                                        <Link
                                            href={
                                                product.brand
                                                    ? `/products?brand=${product.brand.slug}`
                                                    : `/products?category=${product.category?.slug}`
                                            }
                                            className="eyebrow bg-[var(--brand-slate)] px-3 py-2 text-[10px] text-[var(--brand-ivory)]"
                                        >
                                            {product.brand?.name ?? product.category?.name}
                                        </Link>
                                    )}
                                    {product.is_new_arrival && (
                                        <span className="eyebrow border border-[var(--brand-gold)] px-3 py-2 text-[10px] text-[var(--brand-gold-dim)]">
                                            New arrival
                                        </span>
                                    )}
                                </div>

                                <h1 className="font-display text-4xl leading-[0.95] text-[var(--brand-ink)] md:text-6xl">{product.name}</h1>

                                <div className="mt-5 flex flex-wrap items-end gap-3">
                                    <span className="font-display text-4xl text-[var(--brand-ink)]">Tk {effectivePrice.toLocaleString()}</span>
                                    {hasDiscount && (
                                        <>
                                            <span className="pb-1 text-lg text-[var(--brand-muted)] line-through">
                                                Tk {Number(product.compare_price).toLocaleString()}
                                            </span>
                                            <span className="mb-1 bg-[#8E3B2E] px-2 py-1 text-xs font-semibold text-white">-{discountPct}%</span>
                                        </>
                                    )}
                                    <span className="pb-1 text-sm text-[var(--brand-muted)]">per piece</span>
                                </div>

                                <div className="mt-4 flex flex-wrap items-center gap-4 text-sm">
                                    <div className="flex items-center gap-1 text-[var(--brand-gold-dim)]">
                                        {[1, 2, 3, 4, 5].map((star) => (
                                            <Star key={star} size={15} fill="currentColor" />
                                        ))}
                                        <span className="ml-1 text-[var(--brand-muted)]">4.8 reviews</span>
                                    </div>
                                    <span className={`flex items-center gap-2 ${inStock ? 'text-[#4A7A4A]' : 'text-[#8E3B2E]'}`}>
                                        <span className={`h-2 w-2 rounded-full ${inStock ? 'bg-[#4A7A4A]' : 'bg-[#8E3B2E]'}`} />
                                        {inStock ? `${stockQty ?? 0} in stock` : t.common.outOfStock}
                                    </span>
                                </div>

                                {product.short_description && (
                                    <p className="mt-5 text-sm leading-7 text-[var(--brand-muted)]">{product.short_description}</p>
                                )}

                                <div className="my-6 h-px bg-[var(--brand-line)]" />

                                {hasVariants && (
                                    <>
                                        <AttrSelector
                                            groups={attrGroups}
                                            selections={selectedAttrs}
                                            onSelect={handleAttrSelect}
                                            variants={variants}
                                        />
                                        {variantError && (
                                            <p className="mt-4 border border-[var(--brand-gold)] bg-white px-4 py-3 text-sm text-[var(--brand-gold-dim)]">
                                                Please select all options to continue.
                                            </p>
                                        )}
                                        <div className="my-6 h-px bg-[var(--brand-line)]" />
                                    </>
                                )}

                                <UsageSelector selected={usage} onSelect={setUsage} fabricColor={fabricColor} />

                                <div className="mt-6">
                                    <div className="mb-3 flex items-center gap-2">
                                        <Ruler size={15} className="text-[var(--brand-gold)]" />
                                        <span className="eyebrow text-[var(--brand-muted)]">Fabric length</span>
                                    </div>
                                    <div className="flex flex-wrap gap-2">
                                        {lengthOptions.map((option) => (
                                            <button
                                                key={option}
                                                onClick={() => setLength(option)}
                                                className={`border px-3 py-2 text-sm transition ${
                                                    length === option
                                                        ? 'border-[var(--brand-slate)] bg-[var(--brand-slate)] text-[var(--brand-ivory)]'
                                                        : 'border-[var(--brand-line)] bg-white text-[var(--brand-ink)] hover:border-[var(--brand-gold)]'
                                                }`}
                                            >
                                                {option}
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                <div className="mt-7 grid gap-3 sm:grid-cols-[144px_1fr]">
                                    <div className="flex h-13 items-center border border-[var(--brand-line)] bg-white">
                                        <button
                                            onClick={() => setQty((value) => Math.max(1, value - 1))}
                                            className="flex h-13 w-12 items-center justify-center hover:bg-[var(--brand-cream)]"
                                            aria-label="Decrease quantity"
                                        >
                                            <Minus size={15} />
                                        </button>
                                        <span className="flex-1 text-center text-sm font-semibold">{qty}</span>
                                        <button
                                            onClick={() => setQty((value) => value + 1)}
                                            className="flex h-13 w-12 items-center justify-center hover:bg-[var(--brand-cream)]"
                                            aria-label="Increase quantity"
                                        >
                                            <Plus size={15} />
                                        </button>
                                    </div>

                                    <button
                                        onClick={addToCart}
                                        disabled={adding || !inStock}
                                        className={`flex h-13 items-center justify-center gap-2 px-5 text-sm font-semibold transition ${
                                            !inStock
                                                ? 'cursor-not-allowed bg-stone-200 text-stone-400'
                                                : added
                                                  ? 'bg-[#4A7A4A] text-white'
                                                  : 'bg-[var(--brand-slate)] text-[var(--brand-ivory)] hover:bg-[var(--brand-ink)]'
                                        }`}
                                    >
                                        {added ? <Check size={17} /> : <ShoppingCart size={17} />}
                                        {added
                                            ? t.productShow.added
                                            : adding
                                              ? t.productShow.adding
                                              : `${t.common.addToCart} - Tk ${(effectivePrice * qty).toLocaleString()}`}
                                    </button>
                                </div>

                                <div className="mt-3 grid gap-3 sm:grid-cols-2">
                                    <Link
                                        href="/checkout"
                                        className="flex h-12 items-center justify-center border border-[var(--brand-gold)] bg-[var(--brand-gold)] px-5 text-sm font-semibold text-white transition hover:opacity-90"
                                    >
                                        {t.common.buyNow}
                                    </Link>
                                    <button
                                        onClick={() => setPreviewOpen(true)}
                                        className="flex h-12 items-center justify-center gap-2 border border-[var(--brand-line)] bg-white px-5 text-sm font-semibold text-[var(--brand-ink)] transition hover:border-[var(--brand-gold)]"
                                    >
                                        <Sparkles size={16} className="text-[var(--brand-gold)]" />
                                        Preview outfit
                                    </button>
                                </div>

                                <div className="mt-5 grid gap-3 text-xs text-[var(--brand-muted)] sm:grid-cols-3">
                                    <div className="flex items-center gap-2">
                                        <ShieldCheck size={16} className="text-[var(--brand-gold)]" />
                                        Premium fabric
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Truck size={16} className="text-[var(--brand-gold)]" />
                                        Cash on delivery
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Heart size={16} className="text-[var(--brand-gold)]" />
                                        Carefully packed
                                    </div>
                                </div>

                                <div className="mt-5 space-y-1 border-t border-[var(--brand-line)] pt-4 text-xs text-[var(--brand-muted)]">
                                    {product.sku && (
                                        <div>
                                            {t.productShow.sku}: <span className="font-mono text-[var(--brand-ink)]">{product.sku}</span>
                                        </div>
                                    )}
                                    {product.category && (
                                        <div>
                                            {t.productShow.category}:{' '}
                                            <Link
                                                href={`/products?category=${product.category.slug}`}
                                                className="link-gold text-[var(--brand-gold-dim)]"
                                            >
                                                {product.category.name}
                                            </Link>
                                        </div>
                                    )}
                                </div>
                            </aside>
                        </div>

                        <div className="mt-12">
                            <PreviewPanel selected={usage} fabricColor={fabricColor} />
                        </div>

                        <div className="mt-12 grid gap-10 lg:grid-cols-[1fr_380px]">
                            <section className="border border-[var(--brand-line)] bg-[var(--brand-ivory)] px-5 md:px-8">
                                <AccordionItem title="Description" defaultOpen>
                                    {product.description ? (
                                        <div
                                            className="prose prose-sm max-w-none text-[var(--brand-muted)]"
                                            dangerouslySetInnerHTML={{ __html: product.description }}
                                        />
                                    ) : (
                                        <p>{t.productShow.noDescription}</p>
                                    )}
                                </AccordionItem>
                                <AccordionItem title="Fabric Details">
                                    <dl className="grid gap-3 sm:grid-cols-2">
                                        {product.sku && (
                                            <>
                                                <dt className="text-[var(--brand-ink)]">Product code</dt>
                                                <dd>{product.sku}</dd>
                                            </>
                                        )}
                                        {product.weight && (
                                            <>
                                                <dt className="text-[var(--brand-ink)]">Weight</dt>
                                                <dd>
                                                    {product.weight} {t.productShow.kg}
                                                </dd>
                                            </>
                                        )}
                                        <dt className="text-[var(--brand-ink)]">Recommended use</dt>
                                        <dd>{usageOptions.map((option) => option.type).join(', ')}</dd>
                                        <dt className="text-[var(--brand-ink)]">Selected length</dt>
                                        <dd>{length}</dd>
                                    </dl>
                                </AccordionItem>
                                <AccordionItem title="Styling Suggestions">
                                    Choose Punjabi for a traditional look, Shirt for everyday styling, or Kabli for a more formal modest outfit. Pair
                                    darker colours with antique buttons and lighter colours with minimal trim.
                                </AccordionItem>
                                <AccordionItem title="Wash & Care">
                                    Gentle wash separately, dry in shade, and iron on medium heat. For deep colours, test first wash before stitching.
                                </AccordionItem>
                                <AccordionItem title="Delivery & Returns">
                                    Cash on delivery is available. Fabric is checked and packed carefully before dispatch. Return eligibility depends
                                    on unused condition and store policy.
                                </AccordionItem>
                            </section>

                            <aside className="h-fit border border-[var(--brand-line)] bg-white p-5">
                                <div className="eyebrow text-[var(--brand-gold-dim)]">Fabric guide</div>
                                <h2 className="font-display mt-2 text-3xl text-[var(--brand-ink)]">How much fabric?</h2>
                                <div className="mt-5 space-y-3">
                                    {usageOptions.map((option) => (
                                        <div
                                            key={option.type}
                                            className="flex items-center justify-between border-b border-[var(--brand-line)] pb-3 text-sm last:border-0 last:pb-0"
                                        >
                                            <span className="text-[var(--brand-ink)]">{option.type}</span>
                                            <span className="font-medium text-[var(--brand-gold-dim)]">{option.length}</span>
                                        </div>
                                    ))}
                                </div>
                                <p className="mt-5 text-xs leading-6 text-[var(--brand-muted)]">
                                    Measurements vary by body size and tailor pattern. Confirm final length with your tailor before cutting.
                                </p>
                            </aside>
                        </div>

                        {relatedProducts.length > 0 && (
                            <section className="mt-14">
                                <div className="mb-6 flex items-end justify-between gap-4">
                                    <div>
                                        <div className="eyebrow mb-2 text-[var(--brand-gold-dim)]">You may also like</div>
                                        <h2 className="font-display text-4xl text-[var(--brand-ink)]">{t.productShow.relatedProducts}</h2>
                                    </div>
                                    {product.category && (
                                        <Link
                                            href={`/products?category=${product.category.slug}`}
                                            className="link-gold hidden text-sm text-[var(--brand-gold-dim)] sm:block"
                                        >
                                            View all
                                        </Link>
                                    )}
                                </div>
                                <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
                                    {relatedProducts.slice(0, 8).map((related) => (
                                        <RelatedCard key={related.id} product={related} />
                                    ))}
                                </div>
                            </section>
                        )}
                    </div>
                </div>
            </FrontendLayout>

            <FabricPreviewModal product={previewOpen ? product : null} onClose={() => setPreviewOpen(false)} />
        </>
    );
}
