import { Head, Link, router } from '@inertiajs/react';
import { ShoppingCart, X } from 'lucide-react';
import { useRef, useState } from 'react';

import FrontendLayout from '@/layouts/frontend-layout';
import { xsrfToken } from '@/lib/utils';
import { type Brand, type PaginatedData, type Product } from '@/types';

// ─── Decorative SVGs ──────────────────────────────────────────────────────────

function OudBottleSvg({ className = '', style }: { className?: string; style?: React.CSSProperties }) {
    return (
        <svg viewBox="0 0 120 200" fill="none" className={className} style={style} xmlns="http://www.w3.org/2000/svg">
            <rect x="50" y="2" width="20" height="28" rx="4" fill="currentColor" opacity="0.5" />
            <path d="M35 40 C20 60 15 90 15 110 C15 150 30 185 60 188 C90 185 105 150 105 110 C105 90 100 60 85 40 Z" fill="currentColor" opacity="0.15" stroke="currentColor" strokeWidth="1.5" />
            <path d="M45 40 C35 60 32 85 32 105 C32 135 42 168 60 170 C78 168 88 135 88 105 C88 85 85 60 75 40 Z" fill="currentColor" opacity="0.2" />
            <ellipse cx="60" cy="110" rx="20" ry="30" fill="currentColor" opacity="0.1" />
            <path d="M42 70 C50 64 70 64 78 70" stroke="currentColor" strokeWidth="1" opacity="0.4" fill="none" />
            <path d="M38 85 C50 78 70 78 82 85" stroke="currentColor" strokeWidth="0.8" opacity="0.3" fill="none" />
        </svg>
    );
}

function SparklesSvg({ className = '', style }: { className?: string; style?: React.CSSProperties }) {
    return (
        <svg viewBox="0 0 100 100" fill="none" className={className} style={style} xmlns="http://www.w3.org/2000/svg">
            <path d="M50 10 L54 42 L86 46 L54 50 L50 82 L46 50 L14 46 L46 42 Z" fill="currentColor" opacity="0.6" />
            <path d="M20 15 L22 28 L35 30 L22 32 L20 45 L18 32 L5 30 L18 28 Z" fill="currentColor" opacity="0.4" />
            <path d="M80 60 L82 70 L92 72 L82 74 L80 84 L78 74 L68 72 L78 70 Z" fill="currentColor" opacity="0.35" />
        </svg>
    );
}

// ─── Hero ─────────────────────────────────────────────────────────────────────

function FragranceHero({ total }: { total: number }) {
    return (
        <section
            style={{
                background: 'linear-gradient(160deg, #0D0A12 0%, #1A1128 40%, #0F0D1A 100%)',
                position: 'relative',
                overflow: 'hidden',
            }}
        >
            <div
                style={{
                    position: 'absolute', top: '-20%', right: '-10%', width: '600px', height: '600px',
                    borderRadius: '50%', background: 'radial-gradient(circle, rgba(120,80,180,0.18) 0%, transparent 70%)',
                    pointerEvents: 'none',
                }}
            />
            <div
                style={{
                    position: 'absolute', bottom: '-15%', left: '-8%', width: '500px', height: '500px',
                    borderRadius: '50%', background: 'radial-gradient(circle, rgba(184,137,63,0.12) 0%, transparent 70%)',
                    pointerEvents: 'none',
                }}
            />
            <div
                style={{
                    position: 'absolute', top: '30%', left: '50%', transform: 'translateX(-50%)',
                    width: '800px', height: '200px',
                    background: 'radial-gradient(ellipse, rgba(140,90,200,0.08) 0%, transparent 60%)',
                    pointerEvents: 'none',
                }}
            />

            <OudBottleSvg className="pointer-events-none absolute right-[8%] top-[10%] hidden lg:block" style={{ width: '120px', height: 'auto', color: '#B8893F', opacity: 0.35 }} />
            <OudBottleSvg className="pointer-events-none absolute left-[6%] bottom-[8%] hidden lg:block" style={{ width: '80px', height: 'auto', color: '#9B6ED4', opacity: 0.25, transform: 'scaleX(-1)' }} />
            <SparklesSvg className="pointer-events-none absolute right-[20%] bottom-[15%] hidden lg:block" style={{ width: '80px', height: 'auto', color: '#B8893F' }} />
            <SparklesSvg className="pointer-events-none absolute left-[25%] top-[15%] hidden lg:block" style={{ width: '50px', height: 'auto', color: '#9B6ED4' }} />

            <div className="relative mx-auto max-w-[1500px] px-5 py-20 text-center lg:px-10 lg:py-28">
                <div
                    className="mb-6 inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-xs tracking-[0.2em] uppercase"
                    style={{ borderColor: 'rgba(184,137,63,0.35)', background: 'rgba(184,137,63,0.08)', color: '#C9A05A' }}
                >
                    <span style={{ fontSize: '8px' }}>✦</span>
                    Exclusive Collection
                    <span style={{ fontSize: '8px' }}>✦</span>
                </div>

                <h1
                    className="mb-6 font-display"
                    style={{ fontSize: 'clamp(42px, 7vw, 100px)', lineHeight: '0.95', letterSpacing: '-0.02em', color: '#F5EDD8' }}
                >
                    The Scent{' '}
                    <span
                        style={{
                            fontStyle: 'italic',
                            background: 'linear-gradient(135deg, #C9A05A 0%, #E8C878 50%, #B8893F 100%)',
                            WebkitBackgroundClip: 'text',
                            WebkitTextFillColor: 'transparent',
                            backgroundClip: 'text',
                        }}
                    >
                        Collection
                    </span>
                </h1>

                <div className="mb-6 flex items-center justify-center gap-4">
                    <div style={{ width: '60px', height: '1px', background: 'rgba(184,137,63,0.4)' }} />
                    <svg viewBox="0 0 20 20" fill="none" style={{ width: '16px', color: '#C9A05A' }}>
                        <path d="M10 2L12 8L18 10L12 12L10 18L8 12L2 10L8 8Z" fill="currentColor" opacity="0.7" />
                    </svg>
                    <div style={{ width: '60px', height: '1px', background: 'rgba(184,137,63,0.4)' }} />
                </div>

                <p className="mx-auto mb-10 max-w-[540px] text-base leading-[1.75]" style={{ color: 'rgba(220,200,180,0.65)' }}>
                    Rare oud, floral musk, and oriental woods — curated fragrances that leave a lasting impression.
                </p>

                <div
                    className="mx-auto inline-flex items-center gap-6 rounded-full border px-6 py-3"
                    style={{ borderColor: 'rgba(184,137,63,0.2)', background: 'rgba(184,137,63,0.06)' }}
                >
                    <span style={{ color: '#C9A05A', fontVariantNumeric: 'tabular-nums' }} className="text-lg font-semibold">
                        {total}
                    </span>
                    <span style={{ color: 'rgba(220,200,180,0.5)', fontSize: '12px', letterSpacing: '0.12em' }} className="uppercase tracking-widest">
                        Fragrances
                    </span>
                </div>
            </div>

            <div
                style={{
                    position: 'absolute', bottom: 0, left: 0, right: 0, height: '80px',
                    background: 'linear-gradient(to bottom, transparent, #F8F5F0)',
                    pointerEvents: 'none',
                }}
            />
        </section>
    );
}

// ─── Filter Types ─────────────────────────────────────────────────────────────

interface FragranceFilters {
    search?: string;
    brand?: string;
    min_price?: string;
    max_price?: string;
    sort?: string;
    availability?: string;
}

interface FragranceFilterState {
    search: string;
    brand: string;
    min_price: string;
    max_price: string;
    sort: string;
    availability: string;
}

// ─── Filter Accordion ─────────────────────────────────────────────────────────

function FilterAccordion({ title, defaultOpen = true, children }: { title: string; defaultOpen?: boolean; children: React.ReactNode }) {
    const [open, setOpen] = useState(defaultOpen);
    return (
        <div style={{ borderBottom: '1px solid rgba(184,137,63,0.15)' }}>
            <button onClick={() => setOpen((o) => !o)} className="flex w-full items-center justify-between py-4">
                <span style={{ fontSize: '11px', letterSpacing: '0.2em', textTransform: 'uppercase', color: '#1a1614', fontWeight: 500 }}>
                    {title}
                </span>
                <span style={{ color: open ? '#C9A05A' : '#9E8E84', transition: 'color 0.2s' }}>
                    <svg width="10" height="10" viewBox="0 0 10 10">
                        <path
                            d="M5 1v8M1 5h8"
                            stroke="currentColor"
                            strokeWidth="1.4"
                            strokeLinecap="round"
                            style={{ transform: open ? 'rotate(45deg)' : 'none', transformOrigin: 'center', transition: 'transform .3s' }}
                        />
                    </svg>
                </span>
            </button>
            <div style={{ maxHeight: open ? 600 : 0, opacity: open ? 1 : 0, overflow: 'hidden', transition: 'all 0.3s ease' }}>
                <div className="pb-5">{children}</div>
            </div>
        </div>
    );
}

// ─── Filter Body ──────────────────────────────────────────────────────────────

function FragranceFilterBody({
    filters,
    brands,
    onChange,
}: {
    filters: FragranceFilterState;
    brands: Brand[];
    onChange: (updates: Partial<FragranceFilterState>) => void;
}) {
    const checkMark = (
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
            <path d="M1 5l2.5 2.5L9 2" stroke="#FBF7EF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    );

    const radioBox = (active: boolean) => (
        <span
            style={{
                width: '14px', height: '14px', flexShrink: 0,
                border: `1px solid ${active ? '#C9A05A' : 'rgba(184,137,63,0.3)'}`,
                background: active ? '#C9A05A' : 'transparent',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 0.2s',
            }}
        >
            {active && checkMark}
        </span>
    );

    return (
        <div>
            {/* Brands */}
            {brands.length > 0 && (
                <FilterAccordion title="Brand">
                    <ul className="space-y-2.5">
                        <li>
                            <label className="flex cursor-pointer items-center gap-2.5">
                                {radioBox(!filters.brand)}
                                <input type="radio" className="sr-only" checked={!filters.brand} onChange={() => onChange({ brand: '' })} />
                                <span style={{ fontSize: '13px', color: !filters.brand ? '#C9A05A' : '#1a1614' }}>All Brands</span>
                            </label>
                        </li>
                        {brands.map((b) => (
                            <li key={b.id}>
                                <label className="flex cursor-pointer items-center gap-2.5">
                                    {radioBox(filters.brand === b.slug)}
                                    <input type="radio" className="sr-only" checked={filters.brand === b.slug} onChange={() => onChange({ brand: b.slug })} />
                                    <span style={{ fontSize: '13px', color: filters.brand === b.slug ? '#C9A05A' : '#1a1614' }}>{b.name}</span>
                                </label>
                            </li>
                        ))}
                    </ul>
                </FilterAccordion>
            )}

            {/* Price */}
            <FilterAccordion title="Price">
                <div className="flex items-center gap-3">
                    <label className="flex-1">
                        <div style={{ fontSize: '10px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9E8E84', marginBottom: '6px' }}>Min</div>
                        <div style={{ display: 'flex', alignItems: 'center', border: '1px solid rgba(184,137,63,0.2)', background: '#FFFEFB', padding: '7px 10px' }}>
                            <span style={{ fontSize: '11px', color: '#9E8E84', marginRight: '4px' }}>৳</span>
                            <input
                                type="number"
                                value={filters.min_price}
                                onChange={(e) => onChange({ min_price: e.target.value })}
                                placeholder="0"
                                min={0}
                                style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', fontSize: '13px', color: '#1a1614' }}
                            />
                        </div>
                    </label>
                    <span style={{ color: '#9E8E84', marginTop: '20px' }}>—</span>
                    <label className="flex-1">
                        <div style={{ fontSize: '10px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9E8E84', marginBottom: '6px' }}>Max</div>
                        <div style={{ display: 'flex', alignItems: 'center', border: '1px solid rgba(184,137,63,0.2)', background: '#FFFEFB', padding: '7px 10px' }}>
                            <span style={{ fontSize: '11px', color: '#9E8E84', marginRight: '4px' }}>৳</span>
                            <input
                                type="number"
                                value={filters.max_price}
                                onChange={(e) => onChange({ max_price: e.target.value })}
                                placeholder="∞"
                                min={0}
                                style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', fontSize: '13px', color: '#1a1614' }}
                            />
                        </div>
                    </label>
                </div>
            </FilterAccordion>

            {/* Availability */}
            <FilterAccordion title="Availability" defaultOpen={false}>
                <ul className="space-y-2.5">
                    {[{ k: '', l: 'All' }, { k: 'in_stock', l: 'In Stock' }, { k: 'out_of_stock', l: 'Out of Stock' }].map((a) => (
                        <li key={a.k}>
                            <label className="flex cursor-pointer items-center gap-2.5">
                                {radioBox(filters.availability === a.k)}
                                <input type="radio" className="sr-only" checked={filters.availability === a.k} onChange={() => onChange({ availability: a.k })} />
                                <span style={{ fontSize: '13px', color: filters.availability === a.k ? '#C9A05A' : '#1a1614' }}>{a.l}</span>
                            </label>
                        </li>
                    ))}
                </ul>
            </FilterAccordion>
        </div>
    );
}

// ─── Active Filter Chips ──────────────────────────────────────────────────────

function FragranceActiveFilters({
    filters,
    brands,
    onRemove,
    onClear,
}: {
    filters: FragranceFilterState;
    brands: Brand[];
    onRemove: (key: keyof FragranceFilterState) => void;
    onClear: () => void;
}) {
    const chips: { label: string; onRemove: () => void }[] = [];

    if (filters.search) chips.push({ label: `"${filters.search}"`, onRemove: () => onRemove('search') });
    if (filters.brand) {
        const b = brands.find((br) => br.slug === filters.brand);
        chips.push({ label: b?.name ?? filters.brand, onRemove: () => onRemove('brand') });
    }
    if (filters.min_price || filters.max_price) {
        chips.push({
            label: `৳${filters.min_price || '0'} – ৳${filters.max_price || '∞'}`,
            onRemove: () => { onRemove('min_price'); onRemove('max_price'); },
        });
    }
    if (filters.availability) {
        chips.push({
            label: filters.availability === 'in_stock' ? 'In Stock' : 'Out of Stock',
            onRemove: () => onRemove('availability'),
        });
    }

    if (!chips.length) return null;

    return (
        <div className="flex flex-wrap items-center gap-2 pb-5" style={{ borderBottom: '1px solid rgba(184,137,63,0.15)' }}>
            <span style={{ fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: '#9E8E84', marginRight: '4px' }}>Active</span>
            {chips.map((c, i) => (
                <button
                    key={i}
                    onClick={c.onRemove}
                    className="inline-flex items-center gap-1.5 border px-3 py-1.5 text-[12px] transition hover:border-amber-400"
                    style={{ background: '#FFFEFB', borderColor: 'rgba(184,137,63,0.25)', color: '#1a1614' }}
                >
                    {c.label}
                    <X size={9} style={{ color: '#9E8E84' }} />
                </button>
            ))}
            <button
                onClick={onClear}
                className="ml-1 text-[11px] uppercase tracking-[0.16em] underline-offset-4 hover:underline"
                style={{ color: '#C9A05A' }}
            >
                Clear all
            </button>
        </div>
    );
}

// ─── Sort Bar ─────────────────────────────────────────────────────────────────

const SORT_OPTIONS = [
    { value: '', label: 'Featured' },
    { value: 'newest', label: 'Newest' },
    { value: 'price_asc', label: 'Price: Low → High' },
    { value: 'price_desc', label: 'Price: High → Low' },
    { value: 'az', label: 'A → Z' },
    { value: 'za', label: 'Z → A' },
];

function FragranceSortBar({
    count,
    sort,
    onSort,
    cols,
    onCols,
    onMobileFilters,
}: {
    count: number;
    sort: string;
    onSort: (v: string) => void;
    cols: number;
    onCols: (n: number) => void;
    onMobileFilters: () => void;
}) {
    const [open, setOpen] = useState(false);
    const currentLabel = SORT_OPTIONS.find((o) => o.value === sort)?.label ?? 'Featured';

    const colIcons: Record<number, React.ReactNode> = {
        2: <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="1" width="5" height="12" /><rect x="8" y="1" width="5" height="12" /></svg>,
        3: <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="1" width="3.2" height="12" /><rect x="5.4" y="1" width="3.2" height="12" /><rect x="9.8" y="1" width="3.2" height="12" /></svg>,
        4: <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="1" width="2.4" height="5.5" /><rect x="4.4" y="1" width="2.4" height="5.5" /><rect x="7.8" y="1" width="2.4" height="5.5" /><rect x="11.2" y="1" width="2.4" height="5.5" /><rect x="1" y="7.5" width="2.4" height="5.5" /><rect x="4.4" y="7.5" width="2.4" height="5.5" /><rect x="7.8" y="7.5" width="2.4" height="5.5" /><rect x="11.2" y="7.5" width="2.4" height="5.5" /></svg>,
    };

    return (
        <div className="flex flex-wrap items-center justify-between gap-4 py-5" style={{ borderBottom: '1px solid rgba(184,137,63,0.15)' }}>
            <div className="flex items-center gap-4">
                <button
                    onClick={onMobileFilters}
                    className="inline-flex items-center gap-2 border px-4 py-2.5 text-[12px] uppercase tracking-[0.16em] transition lg:hidden"
                    style={{ borderColor: 'rgba(184,137,63,0.25)', color: '#1a1614' }}
                >
                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                        <path d="M1 3h11M3 6.5h7M5 10h3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
                    </svg>
                    Filters
                </button>
                <div className="text-[13px]" style={{ color: '#7A6E65' }}>
                    Showing <span className="font-medium" style={{ color: '#1a1614' }}>{count}</span> fragrances
                </div>
            </div>

            <div className="flex items-center gap-3">
                {/* Column toggle */}
                <div
                    className="hidden items-center gap-0 border md:flex"
                    style={{ borderColor: 'rgba(184,137,63,0.2)', background: '#F8F5F0' }}
                >
                    {[2, 3, 4].map((n) => (
                        <button
                            key={n}
                            onClick={() => onCols(n)}
                            className="flex h-9 w-9 items-center justify-center transition"
                            aria-label={`${n} columns`}
                            style={{
                                background: cols === n ? '#1a1614' : 'transparent',
                                color: cols === n ? '#E8D5A8' : '#9E8E84',
                            }}
                        >
                            {colIcons[n]}
                        </button>
                    ))}
                </div>

                {/* Sort dropdown */}
                <div className="relative">
                    <button
                        onClick={() => setOpen((o) => !o)}
                        className="inline-flex items-center gap-2 border px-4 py-2.5 text-[12px] uppercase tracking-[0.16em] transition"
                        style={{ borderColor: 'rgba(184,137,63,0.2)', background: '#F8F5F0', color: '#1a1614' }}
                    >
                        <span style={{ color: '#9E8E84' }}>Sort:</span>
                        <span>{currentLabel}</span>
                        <svg width="11" height="11" viewBox="0 0 11 11" className={`transition ${open ? 'rotate-180' : ''}`}>
                            <path d="M2 4l3.5 3.5L9 4" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                    </button>
                    {open && (
                        <>
                            <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
                            <div
                                className="absolute right-0 top-full z-40 mt-2 w-[220px] border shadow-lg"
                                style={{ background: '#FFFEFB', borderColor: 'rgba(184,137,63,0.2)' }}
                            >
                                {SORT_OPTIONS.map((o) => (
                                    <button
                                        key={o.value}
                                        onClick={() => { onSort(o.value); setOpen(false); }}
                                        className="block w-full px-5 py-3 text-left text-[13px] transition"
                                        style={{
                                            color: sort === o.value ? '#C9A05A' : '#1a1614',
                                            background: sort === o.value ? 'rgba(184,137,63,0.06)' : 'transparent',
                                        }}
                                    >
                                        {o.label}
                                    </button>
                                ))}
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

// ─── Mobile Filter Drawer ─────────────────────────────────────────────────────

function FragranceMobileFilterDrawer({
    open,
    onClose,
    filters,
    brands,
    onChange,
    onClear,
    resultCount,
}: {
    open: boolean;
    onClose: () => void;
    filters: FragranceFilterState;
    brands: Brand[];
    onChange: (updates: Partial<FragranceFilterState>) => void;
    onClear: () => void;
    resultCount: number;
}) {
    if (!open) return null;
    return (
        <div className="fixed inset-0 z-50 lg:hidden">
            <div className="absolute inset-0 bg-black/40" onClick={onClose} />
            <aside
                className="absolute bottom-0 left-0 top-0 flex w-[88%] max-w-[400px] flex-col"
                style={{ background: '#FFFEFB' }}
            >
                <header
                    className="flex items-center justify-between p-5"
                    style={{ borderBottom: '1px solid rgba(184,137,63,0.15)' }}
                >
                    <div className="flex items-center gap-2">
                        <svg viewBox="0 0 20 20" fill="none" style={{ width: '14px', color: '#C9A05A' }}>
                            <path d="M10 2L12 8L18 10L12 12L10 18L8 12L2 10L8 8Z" fill="currentColor" opacity="0.8" />
                        </svg>
                        <h3 style={{ fontFamily: 'inherit', fontSize: '20px', color: '#1a1614', fontWeight: 600 }}>Refine</h3>
                    </div>
                    <button
                        onClick={onClose}
                        className="flex h-9 w-9 items-center justify-center border transition"
                        style={{ borderColor: 'rgba(184,137,63,0.25)', color: '#1a1614' }}
                    >
                        <X size={12} />
                    </button>
                </header>
                <div className="flex-1 overflow-auto px-5">
                    <FragranceFilterBody filters={filters} brands={brands} onChange={onChange} />
                </div>
                <footer
                    className="flex gap-3 p-5"
                    style={{ borderTop: '1px solid rgba(184,137,63,0.15)', background: '#F8F5F0' }}
                >
                    <button
                        onClick={onClear}
                        className="flex-1 border py-3 text-[12px] uppercase tracking-[0.16em] transition"
                        style={{ borderColor: 'rgba(184,137,63,0.25)', color: '#1a1614' }}
                    >
                        Clear all
                    </button>
                    <button
                        onClick={onClose}
                        className="flex-[1.4] py-3 text-[12px] uppercase tracking-[0.16em] font-medium transition"
                        style={{ background: '#1a1614', color: '#E8D5A8' }}
                    >
                        See {resultCount} results
                    </button>
                </footer>
            </aside>
        </div>
    );
}

// ─── Product Card ─────────────────────────────────────────────────────────────

function FragranceCard({ product }: { product: Product }) {
    const [adding, setAdding] = useState(false);
    const [added, setAdded] = useState(false);
    const primaryImage = product.images?.find((i) => i.is_primary) ?? product.images?.[0];
    const inStock = product.stock_qty > 0;
    const hasDiscount = product.is_discount_active && product.compare_price;

    const addToCart = async () => {
        if (!inStock || adding) { return; }
        setAdding(true);
        try {
            await fetch('/cart/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': xsrfToken(),
                    Accept: 'application/json',
                },
                body: JSON.stringify({ product_id: product.id, qty: 1 }),
            });
            setAdded(true);
            router.reload({ only: ['cartCount'] });
            setTimeout(() => setAdded(false), 2000);
        } finally {
            setAdding(false);
        }
    };

    return (
        <article
            style={{
                background: '#FFFEFB',
                border: '1px solid rgba(184,137,63,0.12)',
                borderRadius: '2px',
                overflow: 'hidden',
                transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                display: 'flex',
                flexDirection: 'column',
            }}
            className="group hover:-translate-y-1 hover:shadow-xl hover:shadow-amber-900/8"
        >
            {/* Image */}
            <div
                style={{
                    position: 'relative',
                    aspectRatio: '3/4',
                    background: 'linear-gradient(145deg, #F9F4EC 0%, #EDE5D8 100%)',
                    overflow: 'hidden',
                }}
            >
                {primaryImage ? (
                    <img
                        src={`/storage/${primaryImage.image}`}
                        alt={product.name}
                        className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.04]"
                    />
                ) : (
                    <div className="flex h-full w-full items-center justify-center">
                        <OudBottleSvg style={{ width: '60px', color: '#B8893F', opacity: 0.4 }} />
                    </div>
                )}

                {/* Badges */}
                <div className="absolute left-3 top-3 flex flex-col gap-1.5">
                    {!inStock && (
                        <span
                            style={{
                                background: 'rgba(15,10,20,0.75)', backdropFilter: 'blur(8px)',
                                color: '#E5D5C0', fontSize: '10px', letterSpacing: '0.1em', padding: '3px 8px', borderRadius: '2px',
                            }}
                        >
                            SOLD OUT
                        </span>
                    )}
                    {hasDiscount && (
                        <span
                            style={{
                                background: 'rgba(120,40,40,0.85)', backdropFilter: 'blur(8px)',
                                color: '#FFD0C0', fontSize: '10px', letterSpacing: '0.08em', padding: '3px 8px', borderRadius: '2px', fontWeight: 600,
                            }}
                        >
                            -{product.discount_percent}%
                        </span>
                    )}
                    {product.is_new_arrival && inStock && (
                        <span
                            style={{
                                background: 'rgba(80,40,120,0.85)', backdropFilter: 'blur(8px)',
                                color: '#DCC8FF', fontSize: '10px', letterSpacing: '0.1em', padding: '3px 8px', borderRadius: '2px',
                            }}
                        >
                            NEW
                        </span>
                    )}
                </div>

                {/* Hover overlay */}
                <div
                    className="absolute inset-0 flex items-end justify-center pb-4 opacity-0 transition-opacity duration-300 group-hover:opacity-100"
                    style={{ background: 'linear-gradient(to top, rgba(10,6,16,0.6) 0%, transparent 50%)' }}
                >
                    <Link
                        href={`/products/${product.slug}`}
                        className="flex items-center gap-2 rounded-full border px-5 py-2 text-xs font-medium uppercase transition-all hover:bg-white/20"
                        style={{
                            borderColor: 'rgba(255,255,255,0.5)', color: '#F5EDD8',
                            backdropFilter: 'blur(8px)', background: 'rgba(255,255,255,0.1)', letterSpacing: '0.12em',
                        }}
                    >
                        View Details
                    </Link>
                </div>
            </div>

            {/* Info */}
            <div
                style={{
                    padding: '18px 20px 20px', flex: 1, display: 'flex', flexDirection: 'column',
                    borderTop: '1px solid rgba(184,137,63,0.1)',
                }}
            >
                {product.brand && (
                    <p style={{ fontSize: '10px', letterSpacing: '0.15em', color: '#B8893F', textTransform: 'uppercase', marginBottom: '4px' }}>
                        {product.brand.name}
                    </p>
                )}

                <h3 className="font-display mb-2 leading-[1.2]" style={{ fontSize: '16px', color: '#1a1614', fontWeight: 600 }}>
                    {product.name}
                </h3>

                {product.short_description && (
                    <p className="mb-3 line-clamp-2 text-xs leading-[1.6]" style={{ color: '#7A6E65', flex: 1 }}>
                        {product.short_description}
                    </p>
                )}

                {/* Price */}
                <div className="mb-4 flex items-baseline gap-2">
                    <span style={{ fontSize: '18px', fontWeight: 700, color: hasDiscount ? '#8A2020' : '#1a1614', letterSpacing: '-0.01em' }}>
                        ৳{Number(product.price).toLocaleString()}
                    </span>
                    {hasDiscount && (
                        <span style={{ fontSize: '13px', color: '#9E8E84', textDecoration: 'line-through' }}>
                            ৳{Number(product.compare_price).toLocaleString()}
                        </span>
                    )}
                </div>

                {/* Stock indicator */}
                <div className="mb-4 flex items-center gap-1.5">
                    <span
                        style={{
                            width: '6px', height: '6px', borderRadius: '50%',
                            background: inStock ? '#2D7A4A' : '#9E3030',
                            display: 'inline-block', flexShrink: 0,
                        }}
                    />
                    <span style={{ fontSize: '11px', color: inStock ? '#2D7A4A' : '#9E3030', letterSpacing: '0.05em' }}>
                        {inStock ? `In Stock (${product.stock_qty} available)` : 'Out of Stock'}
                    </span>
                </div>

                {/* Add to Cart */}
                <button
                    onClick={addToCart}
                    disabled={!inStock || adding}
                    style={{
                        width: '100%', padding: '11px 0', fontSize: '12px', letterSpacing: '0.12em',
                        fontWeight: 600, textTransform: 'uppercase', borderRadius: '2px',
                        cursor: inStock ? 'pointer' : 'not-allowed', transition: 'all 0.2s ease',
                        background: added ? '#2D7A4A' : inStock ? 'linear-gradient(135deg, #1a1614 0%, #2D2420 100%)' : '#E5E0DC',
                        color: added ? '#E8F5EE' : inStock ? '#E8D5A8' : '#A09590',
                        border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px',
                    }}
                >
                    {added ? (
                        <>
                            <svg viewBox="0 0 20 20" fill="currentColor" style={{ width: '14px', height: '14px' }}>
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clipRule="evenodd" />
                            </svg>
                            Added to Cart
                        </>
                    ) : !inStock ? (
                        'Unavailable'
                    ) : adding ? (
                        'Adding…'
                    ) : (
                        <>
                            <ShoppingCart size={14} />
                            Add to Cart
                        </>
                    )}
                </button>
            </div>
        </article>
    );
}

// ─── Empty State ──────────────────────────────────────────────────────────────

function EmptyState({ hasFilters, onClear }: { hasFilters: boolean; onClear: () => void }) {
    return (
        <div className="py-24 text-center">
            <OudBottleSvg style={{ width: '80px', height: 'auto', color: '#B8893F', opacity: 0.3, margin: '0 auto 24px' }} />
            <h3 className="font-display mb-2 text-2xl" style={{ color: '#1a1614' }}>
                {hasFilters ? 'No Results Found' : 'No Fragrances Yet'}
            </h3>
            <p className="text-sm" style={{ color: '#9E8E84' }}>
                {hasFilters ? 'Try adjusting your filters.' : 'New arrivals coming soon. Stay tuned.'}
            </p>
            {hasFilters && (
                <button
                    onClick={onClear}
                    className="mt-5 px-6 py-2.5 text-[12px] uppercase tracking-[0.16em] transition"
                    style={{ background: '#1a1614', color: '#E8D5A8', borderRadius: '2px' }}
                >
                    Clear Filters
                </button>
            )}
        </div>
    );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function FragrancePage({
    products,
    brands,
    filters: serverFilters,
}: {
    products: PaginatedData<Product>;
    brands: Brand[];
    filters: FragranceFilters;
}) {
    const [localFilters, setLocalFilters] = useState<FragranceFilterState>({
        search: serverFilters.search ?? '',
        brand: serverFilters.brand ?? '',
        min_price: serverFilters.min_price ?? '',
        max_price: serverFilters.max_price ?? '',
        sort: serverFilters.sort ?? '',
        availability: serverFilters.availability ?? '',
    });

    const [cols, setCols] = useState(() => {
        try { return Number(localStorage.getItem('fragrance-cols')) || 3; } catch { return 3; }
    });
    const [mobileFilters, setMobileFilters] = useState(false);
    const priceTimer = useRef<ReturnType<typeof setTimeout>>();

    const hasFilters = !!(
        localFilters.search || localFilters.brand || localFilters.min_price ||
        localFilters.max_price || localFilters.availability
    );

    const navigate = (updates: Partial<FragranceFilterState>) => {
        const next = { ...localFilters, ...updates };
        setLocalFilters(next);
        router.visit('/fragrance', { data: next, preserveState: true, preserveScroll: false });
    };

    const navigateDebounced = (updates: Partial<FragranceFilterState>) => {
        const next = { ...localFilters, ...updates };
        setLocalFilters(next);
        clearTimeout(priceTimer.current);
        priceTimer.current = setTimeout(() => {
            router.visit('/fragrance', { data: next, preserveState: true });
        }, 500);
    };

    const handleFilterChange = (updates: Partial<FragranceFilterState>) => {
        const hasPriceChange = 'min_price' in updates || 'max_price' in updates;
        if (hasPriceChange) {
            navigateDebounced(updates);
        } else {
            navigate(updates);
        }
    };

    const clearAll = () => {
        const empty: FragranceFilterState = { search: '', brand: '', min_price: '', max_price: '', sort: '', availability: '' };
        setLocalFilters(empty);
        router.visit('/fragrance');
    };

    const removeFilter = (key: keyof FragranceFilterState) => {
        if (key === 'min_price' || key === 'max_price') {
            navigate({ min_price: '', max_price: '' });
        } else {
            navigate({ [key]: '' });
        }
    };

    const gridCols =
        cols === 2 ? 'grid-cols-2'
        : cols === 4 ? 'grid-cols-2 lg:grid-cols-4'
        : 'grid-cols-2 lg:grid-cols-3';

    return (
        <FrontendLayout>
            <Head title="Fragrance Collection" />

            <main>
                <FragranceHero total={products.total} />

                {/* Filter + Grid */}
                <section style={{ background: '#F8F5F0', padding: 'clamp(40px, 5vw, 64px) 0' }}>
                    <div className="mx-auto max-w-[1500px] px-5 lg:px-10">
                        <div className="grid gap-10 lg:grid-cols-[280px_1fr] lg:gap-14">

                            {/* Desktop Sidebar */}
                            <aside className="hidden lg:block">
                                <div className="sticky top-[94px]">
                                    <div
                                        className="mb-1 flex items-center gap-2.5 pb-5"
                                        style={{ borderBottom: '1px solid rgba(184,137,63,0.15)' }}
                                    >
                                        <svg viewBox="0 0 20 20" fill="none" style={{ width: '14px', color: '#C9A05A' }}>
                                            <path d="M10 2L12 8L18 10L12 12L10 18L8 12L2 10L8 8Z" fill="currentColor" opacity="0.8" />
                                        </svg>
                                        <h2 style={{ fontSize: '20px', color: '#1a1614', fontWeight: 600 }}>Refine</h2>
                                    </div>
                                    <FragranceFilterBody filters={localFilters} brands={brands} onChange={handleFilterChange} />
                                    <button
                                        onClick={clearAll}
                                        className="mt-5 w-full border py-3 text-[12px] uppercase tracking-[0.16em] transition"
                                        style={{ borderColor: 'rgba(184,137,63,0.2)', color: '#9E8E84' }}
                                        onMouseEnter={(e) => { e.currentTarget.style.color = '#C9A05A'; }}
                                        onMouseLeave={(e) => { e.currentTarget.style.color = '#9E8E84'; }}
                                    >
                                        Clear all filters
                                    </button>
                                </div>
                            </aside>

                            {/* Product Grid */}
                            <section>
                                <FragranceActiveFilters
                                    filters={localFilters}
                                    brands={brands}
                                    onRemove={removeFilter}
                                    onClear={clearAll}
                                />
                                <FragranceSortBar
                                    count={products.total}
                                    sort={localFilters.sort}
                                    onSort={(v) => navigate({ sort: v })}
                                    cols={cols}
                                    onCols={(n) => {
                                        setCols(n);
                                        try { localStorage.setItem('fragrance-cols', String(n)); } catch {}
                                    }}
                                    onMobileFilters={() => setMobileFilters(true)}
                                />

                                {products.data.length === 0 ? (
                                    <EmptyState hasFilters={hasFilters} onClear={clearAll} />
                                ) : (
                                    <>
                                        <div className={`mt-8 grid gap-5 ${gridCols}`}>
                                            {products.data.map((product) => (
                                                <FragranceCard key={product.id} product={product} />
                                            ))}
                                        </div>

                                        {/* Pagination */}
                                        {products.last_page > 1 && (
                                            <div
                                                className="mt-12 flex flex-col items-center justify-between gap-4 border-t pt-8 sm:flex-row"
                                                style={{ borderColor: 'rgba(184,137,63,0.15)' }}
                                            >
                                                <div style={{ fontSize: '12px', letterSpacing: '0.08em', color: '#9E8E84' }}>
                                                    Page {products.current_page} of {products.last_page} · {products.from}–{products.to} of {products.total}
                                                </div>
                                                <div className="flex items-center gap-1">
                                                    {products.links.map((link, i) => (
                                                        <button
                                                            key={i}
                                                            disabled={!link.url}
                                                            onClick={() => link.url && router.visit(link.url)}
                                                            className="min-w-[40px] h-10 border px-3 text-[13px] transition disabled:opacity-30"
                                                            style={{
                                                                background: link.active ? '#1a1614' : 'transparent',
                                                                borderColor: link.active ? '#1a1614' : 'rgba(184,137,63,0.2)',
                                                                color: link.active ? '#E8D5A8' : '#7A6E65',
                                                                cursor: link.url ? 'pointer' : 'not-allowed',
                                                            }}
                                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                                        />
                                                    ))}
                                                </div>
                                            </div>
                                        )}
                                    </>
                                )}
                            </section>
                        </div>
                    </div>
                </section>
            </main>

            <FragranceMobileFilterDrawer
                open={mobileFilters}
                onClose={() => setMobileFilters(false)}
                filters={localFilters}
                brands={brands}
                onChange={handleFilterChange}
                onClear={clearAll}
                resultCount={products.total}
            />
        </FrontendLayout>
    );
}
