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

import FabricPreviewModal from '@/components/fabric-preview-modal';
import SiteHeader from '@/components/site-header';
import { LangProvider } from '@/lib/lang';
import { xsrfToken } from '@/lib/utils';
import { type Attribute, type Brand, type Category, type PaginatedData, type Product, type SharedData } from '@/types';

// ─── Brand Primitives ─────────────────────────────────────────────────────────

function DiamondGlyph({ size = 16, stroke = 'currentColor', className = '' }: { size?: number; stroke?: string; className?: string }) {
    return (
        <svg width={size} height={size} viewBox="0 0 48 48" fill="none" className={className}>
            <path d="M24 3L45 24L24 45L3 24Z" stroke={stroke} strokeWidth="1.5" />
            <path d="M24 10.5L37.5 24L24 37.5L10.5 24Z" stroke={stroke} strokeWidth="1" />
        </svg>
    );
}

// ─── Collection Hero ──────────────────────────────────────────────────────────

function CollectionHero({ count, total, categoryName }: { count: number; total: number; categoryName?: string }) {
    return (
        <section
            className="relative border-b ornament-bg"
            style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}
        >
            <div className="pointer-events-none absolute -top-6 right-10 hidden opacity-20 lg:block">
                <DiamondGlyph size={120} stroke="var(--brand-gold)" />
            </div>
            <div className="pointer-events-none absolute -bottom-6 left-10 hidden opacity-15 lg:block">
                <DiamondGlyph size={80} stroke="var(--brand-gold)" />
            </div>

            <div className="relative mx-auto max-w-[1500px] px-5 py-14 lg:px-10 lg:py-20">
                <nav className="eyebrow mb-6 flex items-center gap-2" style={{ color: 'var(--brand-muted)' }}>
                    <Link href="/" className="transition hover:text-gold" style={{ color: 'inherit' }}>Home</Link>
                    <span className="opacity-50">/</span>
                    <span style={{ color: 'var(--brand-ink)' }}>{categoryName ?? 'All Products'}</span>
                </nav>

                <div className="grid items-end gap-8 lg:grid-cols-12">
                    <div className="lg:col-span-8">
                        <div className="eyebrow mb-4 flex items-center gap-3" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>
                            <DiamondGlyph size={12} stroke="var(--brand-gold)" />
                            The Full Wardrobe
                        </div>
                        <h1
                            className="font-display leading-[0.96] tracking-[-0.015em]"
                            style={{ fontSize: 'clamp(48px, 7.5vw, 96px)', color: 'var(--brand-ink)' }}
                        >
                            {categoryName ? (
                                <>
                                    <span className="italic" style={{ color: 'var(--brand-gold)' }}>{categoryName}</span>
                                </>
                            ) : (
                                <>
                                    All{' '}
                                    <span className="italic" style={{ color: 'var(--brand-gold)' }}>
                                        Products
                                    </span>
                                </>
                            )}
                        </h1>
                        <p className="mt-5 max-w-[560px] text-base leading-[1.7]" style={{ color: 'var(--brand-muted)' }}>
                            Explore refined modest wear crafted for comfort, faith, and timeless elegance — from everyday wear to celebratory Eid pieces.
                        </p>
                    </div>

                    <div className="lg:col-span-4 lg:text-right">
                        <div
                            className="inline-flex items-center gap-4 border p-5"
                            style={{ backgroundColor: 'var(--brand-cream)', borderColor: 'var(--brand-line)' }}
                        >
                            <div>
                                <div className="font-display text-[32px] leading-none" style={{ color: 'var(--brand-ink)' }}>
                                    {count}
                                </div>
                                <div className="eyebrow mt-1" style={{ color: 'var(--brand-muted)' }}>
                                    {count === total ? 'Pieces in collection' : `of ${total} pieces`}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
}

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

function FilterAccordion({
    title,
    defaultOpen = true,
    children,
}: {
    title: string;
    defaultOpen?: boolean;
    children: React.ReactNode;
}) {
    const [open, setOpen] = useState(defaultOpen);
    return (
        <div className="border-b" style={{ borderColor: 'var(--brand-line)' }}>
            <button
                onClick={() => setOpen((o) => !o)}
                className="group flex w-full items-center justify-between py-5"
            >
                <span
                    className="text-[13px] uppercase tracking-[0.2em] font-medium"
                    style={{ color: 'var(--brand-ink)' }}
                >
                    {title}
                </span>
                <span
                    className="flex h-6 w-6 items-center justify-center transition"
                    style={{ color: open ? 'var(--brand-gold)' : 'var(--brand-muted)' }}
                >
                    <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
                className="overflow-hidden transition-all duration-300"
                style={{ maxHeight: open ? 600 : 0, opacity: open ? 1 : 0 }}
            >
                <div className="pb-6">{children}</div>
            </div>
        </div>
    );
}

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

interface FilterState {
    search: string;
    category: string;
    min_price: string;
    max_price: string;
    sort: string;
    attr: string[];
    availability: string;
}

function FilterBody({
    filters,
    categories,
    attributes,
    onChange,
}: {
    filters: FilterState;
    categories: Category[];
    attributes: Attribute[];
    onChange: (updates: Partial<FilterState>) => void;
}) {
    const togAttr = (slug: string) => {
        const arr = filters.attr.includes(slug) ? filters.attr.filter((s) => s !== slug) : [...filters.attr, slug];
        onChange({ attr: arr });
    };

    return (
        <div>
            {/* Categories */}
            <FilterAccordion title="Categories">
                <ul className="space-y-2.5">
                    <li>
                        <label className="flex cursor-pointer items-center justify-between group">
                            <span className="flex items-center gap-3">
                                <span
                                    className="flex h-4 w-4 items-center justify-center border transition"
                                    style={{
                                        backgroundColor: !filters.category ? 'var(--brand-gold)' : 'transparent',
                                        borderColor: !filters.category ? 'var(--brand-gold)' : 'var(--brand-line)',
                                    }}
                                >
                                    {!filters.category && (
                                        <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>
                                    )}
                                </span>
                                <input type="radio" className="sr-only" checked={!filters.category} onChange={() => onChange({ category: '' })} />
                                <span className="text-[14px] transition" style={{ color: !filters.category ? 'var(--brand-gold)' : 'var(--brand-ink)' }}>
                                    All Products
                                </span>
                            </span>
                        </label>
                    </li>
                    {categories.map((c) => (
                        <li key={c.id}>
                            <label className="flex cursor-pointer items-center justify-between group">
                                <span className="flex items-center gap-3">
                                    <span
                                        className="flex h-4 w-4 items-center justify-center border transition"
                                        style={{
                                            backgroundColor: filters.category === c.slug ? 'var(--brand-gold)' : 'transparent',
                                            borderColor: filters.category === c.slug ? 'var(--brand-gold)' : 'var(--brand-line)',
                                        }}
                                    >
                                        {filters.category === c.slug && (
                                            <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>
                                        )}
                                    </span>
                                    <input type="radio" className="sr-only" checked={filters.category === c.slug} onChange={() => onChange({ category: c.slug })} />
                                    <span
                                        className="text-[14px] transition group-hover:text-gold"
                                        style={{ color: filters.category === c.slug ? 'var(--brand-gold)' : 'var(--brand-ink)' }}
                                    >
                                        {c.name}
                                    </span>
                                </span>
                            </label>
                        </li>
                    ))}
                </ul>
            </FilterAccordion>

            {/* Price */}
            <FilterAccordion title="Price">
                <div className="flex items-center gap-3">
                    <label className="flex-1">
                        <div className="eyebrow mb-1.5" style={{ color: 'var(--brand-muted)' }}>Min</div>
                        <div
                            className="flex items-center border px-3 py-2 transition focus-within:border-gold"
                            style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}
                        >
                            <span className="mr-1 text-[12px]" style={{ color: 'var(--brand-muted)' }}>৳</span>
                            <input
                                type="number"
                                value={filters.min_price}
                                onChange={(e) => onChange({ min_price: e.target.value })}
                                placeholder="0"
                                min={0}
                                className="w-full bg-transparent text-[13px] outline-none"
                                style={{ color: 'var(--brand-ink)' }}
                            />
                        </div>
                    </label>
                    <span className="mt-5" style={{ color: 'var(--brand-muted)' }}>—</span>
                    <label className="flex-1">
                        <div className="eyebrow mb-1.5" style={{ color: 'var(--brand-muted)' }}>Max</div>
                        <div
                            className="flex items-center border px-3 py-2 transition focus-within:border-gold"
                            style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}
                        >
                            <span className="mr-1 text-[12px]" style={{ color: 'var(--brand-muted)' }}>৳</span>
                            <input
                                type="number"
                                value={filters.max_price}
                                onChange={(e) => onChange({ max_price: e.target.value })}
                                placeholder="∞"
                                min={0}
                                className="w-full bg-transparent text-[13px] outline-none"
                                style={{ color: 'var(--brand-ink)' }}
                            />
                        </div>
                    </label>
                </div>
            </FilterAccordion>

            {/* Attributes (Size, Color, etc.) */}
            {attributes
                .filter((a) => (a.values?.length ?? 0) > 0)
                .map((attr) => (
                    <FilterAccordion key={attr.id} title={attr.name} defaultOpen={false}>
                        <div className="flex flex-wrap gap-2">
                            {attr.values?.map((val) => {
                                const active = filters.attr.includes(val.slug);
                                return (
                                    <button
                                        key={val.id}
                                        onClick={() => togAttr(val.slug)}
                                        className="min-w-[44px] border px-3 py-2 text-[12px] tracking-wider transition"
                                        style={{
                                            backgroundColor: active ? 'var(--brand-slate)' : 'transparent',
                                            borderColor: active ? 'var(--brand-slate)' : 'var(--brand-line)',
                                            color: active ? '#FBF7EF' : 'var(--brand-ink)',
                                        }}
                                    >
                                        {val.value}
                                    </button>
                                );
                            })}
                        </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-3 group">
                                <span
                                    className="flex h-4 w-4 items-center justify-center border transition"
                                    style={{
                                        backgroundColor: filters.availability === a.k ? 'var(--brand-gold)' : 'transparent',
                                        borderColor: filters.availability === a.k ? 'var(--brand-gold)' : 'var(--brand-line)',
                                    }}
                                >
                                    {filters.availability === a.k && (
                                        <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>
                                    )}
                                </span>
                                <input type="radio" className="sr-only" checked={filters.availability === a.k} onChange={() => onChange({ availability: a.k })} />
                                <span
                                    className="text-[14px] transition group-hover:text-gold"
                                    style={{ color: filters.availability === a.k ? 'var(--brand-gold)' : 'var(--brand-ink)' }}
                                >
                                    {a.l}
                                </span>
                            </label>
                        </li>
                    ))}
                </ul>
            </FilterAccordion>
        </div>
    );
}

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

function ActiveFilters({
    filters,
    categories,
    attributes,
    onRemove,
    onClear,
}: {
    filters: FilterState;
    categories: Category[];
    attributes: Attribute[];
    onRemove: (key: keyof FilterState, value?: string) => void;
    onClear: () => void;
}) {
    const chips: { label: string; onRemove: () => void }[] = [];

    if (filters.search) chips.push({ label: `"${filters.search}"`, onRemove: () => onRemove('search') });
    if (filters.category) {
        const cat = categories.find((c) => c.slug === filters.category);
        chips.push({ label: cat?.name ?? filters.category, onRemove: () => onRemove('category') });
    }
    if (filters.min_price || filters.max_price) {
        chips.push({
            label: `৳${filters.min_price || '0'} – ৳${filters.max_price || '∞'}`,
            onRemove: () => onRemove('min_price'),
        });
    }
    filters.attr.forEach((slug) => {
        const val = attributes.flatMap((a) => a.values ?? []).find((v) => v.slug === slug);
        if (val) chips.push({ label: val.value, onRemove: () => onRemove('attr', slug) });
    });
    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 border-b pb-6" style={{ borderColor: 'var(--brand-line)' }}>
            <span className="eyebrow mr-1" style={{ color: 'var(--brand-muted)' }}>Active</span>
            {chips.map((c, i) => (
                <button
                    key={i}
                    onClick={c.onRemove}
                    className="group inline-flex items-center gap-2 border px-3 py-1.5 text-[12px] transition hover:text-gold"
                    style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)', color: 'var(--brand-ink)' }}
                >
                    {c.label}
                    <X size={10} style={{ color: 'var(--brand-muted)' }} />
                </button>
            ))}
            <button
                onClick={onClear}
                className="ml-1 text-[12px] uppercase tracking-[0.16em] underline-offset-4 hover:underline"
                style={{ color: 'var(--brand-gold)' }}
            >
                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 SortBar({
    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';

    return (
        <div className="flex flex-wrap items-center justify-between gap-4 border-b py-5" style={{ borderColor: 'var(--brand-line)' }}>
            <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 hover:text-gold lg:hidden"
                    style={{ borderColor: 'rgba(31,42,48,0.25)', color: 'var(--brand-ink)' }}
                >
                    <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: 'var(--brand-muted)' }}>
                    Showing <span className="font-medium" style={{ color: 'var(--brand-ink)' }}>{count}</span> products
                </div>
            </div>

            <div className="flex items-center gap-3">
                {/* Column toggle */}
                <div className="hidden items-center gap-1 border md:flex" style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-ivory)' }}>
                    {[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={{
                                backgroundColor: cols === n ? 'var(--brand-slate)' : 'transparent',
                                color: cols === n ? '#FBF7EF' : 'var(--brand-muted)',
                            }}
                        >
                            <ColIcon n={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: 'var(--brand-line)', backgroundColor: 'var(--brand-ivory)', color: 'var(--brand-ink)' }}
                    >
                        <span style={{ color: 'var(--brand-muted)' }}>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={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}
                            >
                                {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 hover:bg-cream"
                                        style={{ color: sort === o.value ? 'var(--brand-gold)' : 'var(--brand-ink)', backgroundColor: sort === o.value ? 'var(--brand-cream)' : 'transparent' }}
                                    >
                                        {o.label}
                                    </button>
                                ))}
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

function ColIcon({ n }: { n: number }) {
    if (n === 2) return <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>;
    if (n === 3) return <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>;
    return <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>;
}

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

function ProductCard({
    product,
    wished,
    onWish,
    onQuickView,
    onPreview,
}: {
    product: Product;
    wished: boolean;
    onWish: (id: number) => void;
    onQuickView: (p: Product) => void;
    onPreview: (p: Product) => void;
}) {
    const img = product.images?.find((i) => i.is_primary) ?? product.images?.[0];
    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 inStock = product.stock_qty > 0;
    const [hover, setHover] = useState(false);
    const [adding, setAdding] = useState(false);
    const [added, setAdded] = useState(false);

    const badge = product.is_new_arrival ? { label: 'New', bg: 'var(--brand-gold)', fg: 'var(--brand-slate)' }
        : product.is_best_seller ? { label: 'Best Seller', bg: 'var(--brand-slate)', fg: '#FBF7EF' }
        : product.is_featured ? { label: 'Featured', bg: 'var(--brand-slate)', fg: '#FBF7EF' }
        : null;

    const addToCart = (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        if (product.has_variant) {
            // Navigate to product page for variant selection
            router.visit(`/products/${product.slug}`);
            return;
        }
        setAdding(true);
        fetch('/cart/add', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': xsrfToken() },
            body: JSON.stringify({ product_id: product.id, qty: 1 }),
        })
            .then(() => {
                setAdded(true);
                router.reload({ only: [] });
                setTimeout(() => setAdded(false), 2200);
            })
            .finally(() => setAdding(false));
    };

    return (
        <article
            className="card-lift group block"
            onMouseEnter={() => setHover(true)}
            onMouseLeave={() => setHover(false)}
        >
            {/* Image */}
            <div
                className="relative overflow-hidden border"
                style={{ aspectRatio: '3/4', borderColor: 'var(--brand-line)' }}
            >
                {img ? (
                    <img
                        src={`/storage/${img.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 ph-stripe"
                    >
                        <DiamondGlyph size={36} stroke="rgba(184,137,63,0.3)" />
                    </div>
                )}

                {/* Sold out overlay */}
                {!inStock && (
                    <div className="absolute inset-0 flex items-center justify-center backdrop-blur-[1px]" style={{ backgroundColor: 'rgba(246,241,231,0.65)' }}>
                        <span className="eyebrow px-4 py-2" style={{ backgroundColor: 'var(--brand-slate)', color: '#FBF7EF' }}>
                            Sold Out
                        </span>
                    </div>
                )}

                {/* Badges */}
                <div className="absolute left-3 top-3 right-3 flex items-start justify-between pointer-events-none">
                    <div className="flex flex-col gap-1.5 pointer-events-auto">
                        {badge && (
                            <span className="eyebrow px-2.5 py-1" style={{ backgroundColor: badge.bg, color: badge.fg }}>
                                {badge.label}
                            </span>
                        )}
                        {hasDiscount && (
                            <span className="eyebrow px-2.5 py-1" style={{ backgroundColor: '#8E3B2E', color: '#FBF7EF' }}>
                                -{discountPct}%
                            </span>
                        )}
                    </div>
                    <div className="flex flex-col gap-1.5 pointer-events-auto">
                        <button
                            onClick={(e) => { e.preventDefault(); e.stopPropagation(); onWish(product.id); }}
                            className="flex h-9 w-9 items-center justify-center rounded-full backdrop-blur transition"
                            aria-label="Wishlist"
                            style={{ backgroundColor: 'rgba(251,247,239,0.9)', color: wished ? 'var(--brand-gold)' : 'var(--brand-slate)' }}
                        >
                            <svg width="14" height="14" viewBox="0 0 20 20" fill={wished ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.4">
                                <path d="M10 17.5l-1-1C5 12.5 2.5 10.4 2.5 7.7 2.5 5.7 4 4 6 4c1.5 0 2.9.7 4 1.9C11.1 4.7 12.5 4 14 4c2 0 3.5 1.7 3.5 3.7 0 2.7-2.5 4.8-6.5 8.8l-1 1z" />
                            </svg>
                        </button>
                        <button
                            onClick={(e) => { e.preventDefault(); e.stopPropagation(); onQuickView(product); }}
                            className="flex h-9 w-9 items-center justify-center rounded-full backdrop-blur transition hover:text-gold"
                            aria-label="Quick view"
                            style={{ backgroundColor: 'rgba(251,247,239,0.9)', color: 'var(--brand-slate)' }}
                        >
                            <svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4">
                                <circle cx="10" cy="10" r="3" />
                                <path d="M1 10s3-6 9-6 9 6 9 6-3 6-9 6-9-6-9-6z" />
                            </svg>
                        </button>
                    </div>
                </div>

                {/* Hover quick-add */}
                {inStock && (
                    <div
                        className="absolute inset-x-3 bottom-3 transition-all duration-300"
                        style={{ transform: hover ? 'translateY(0)' : 'translateY(12px)', opacity: hover ? 1 : 0 }}
                    >
                        <div className="flex items-center gap-2 p-2.5 backdrop-blur" style={{ backgroundColor: 'rgba(246,241,231,0.95)' }}>
                            {product.has_variant ? (
                                <Link
                                    href={`/products/${product.slug}`}
                                    className="w-full py-1.5 text-center text-[10px] uppercase tracking-wider text-white transition eyebrow"
                                    style={{ backgroundColor: 'var(--brand-slate)' }}
                                    onClick={(e) => e.stopPropagation()}
                                >
                                    Select Options →
                                </Link>
                            ) : (
                                <button
                                    onClick={addToCart}
                                    disabled={adding}
                                    className="w-full py-1.5 text-[10px] uppercase tracking-wider text-white transition eyebrow disabled:opacity-60"
                                    style={{ backgroundColor: added ? 'var(--brand-gold)' : 'var(--brand-slate)' }}
                                >
                                    {added ? '✓ Added' : adding ? 'Adding…' : '+ Add to Cart'}
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* Info */}
            <Link href={`/products/${product.slug}`} className="mt-4 block">
                <div className="eyebrow mb-1.5" style={{ color: 'var(--brand-gold)' }}>
                    {product.category?.name ?? 'Product'}
                </div>
                <div className="font-display truncate text-[20px] leading-tight" style={{ color: 'var(--brand-ink)' }}>
                    {product.name}
                </div>
                <div className="mt-2 flex items-baseline gap-2">
                    <span className="text-[15px] font-medium" style={{ color: 'var(--brand-ink)' }}>
                        ৳ {Number(product.price).toLocaleString()}
                    </span>
                    {hasDiscount && (
                        <span className="text-[12px] line-through" style={{ color: 'var(--brand-muted)' }}>
                            ৳ {Number(product.compare_price).toLocaleString()}
                        </span>
                    )}
                </div>
            </Link>

            {/* Fabric outfit preview button — always visible, works on mobile */}
            <button
                onClick={() => onPreview(product)}
                className="mt-2.5 w-full border py-2 eyebrow text-[10px] tracking-[0.18em] transition-colors"
                style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-gold)' }}
                onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = 'rgba(184,137,63,0.06)';
                    e.currentTarget.style.borderColor = 'var(--brand-gold)';
                }}
                onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent';
                    e.currentTarget.style.borderColor = 'var(--brand-line)';
                }}
            >
                ✦ Preview as Outfit
            </button>
        </article>
    );
}

// ─── Quick View Modal ─────────────────────────────────────────────────────────

function QuickViewModal({ product, onClose }: { product: Product | null; onClose: () => void }) {
    const [adding, setAdding] = useState(false);
    const [added, setAdded] = useState(false);

    useEffect(() => {
        if (product) { setAdded(false); setAdding(false); }
    }, [product]);

    if (!product) return null;

    const img = product.images?.find((i) => i.is_primary) ?? product.images?.[0];
    const hasDiscount = product.compare_price && Number(product.compare_price) > Number(product.price);

    const addToCart = () => {
        if (product.has_variant) {
            router.visit(`/products/${product.slug}`);
            onClose();
            return;
        }
        setAdding(true);
        fetch('/cart/add', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': xsrfToken() },
            body: JSON.stringify({ product_id: product.id, qty: 1 }),
        })
            .then(() => { setAdded(true); router.reload({ only: [] }); setTimeout(() => setAdded(false), 2000); })
            .finally(() => setAdding(false));
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 lg:p-8">
            <div
                className="absolute inset-0 backdrop-blur-sm"
                style={{ backgroundColor: 'rgba(31,42,48,0.55)' }}
                onClick={onClose}
            />
            <div
                className="relative grid w-full max-w-[900px] overflow-hidden shadow-2xl lg:grid-cols-2"
                style={{ backgroundColor: 'var(--brand-cream)' }}
            >
                <button
                    onClick={onClose}
                    aria-label="Close"
                    className="absolute right-4 top-4 z-10 flex h-10 w-10 items-center justify-center rounded-full border transition hover:text-gold"
                    style={{ backgroundColor: 'rgba(246,241,231,0.9)', borderColor: 'var(--brand-line)', color: 'var(--brand-ink)' }}
                >
                    <X size={14} />
                </button>

                {/* Image */}
                <div style={{ aspectRatio: '4/5', backgroundColor: 'var(--brand-ivory)' }}>
                    {img ? (
                        <img src={`/storage/${img.image}`} alt={product.name} className="h-full w-full object-cover" />
                    ) : (
                        <div className="flex h-full items-center justify-center ph-stripe">
                            <DiamondGlyph size={48} stroke="rgba(184,137,63,0.3)" />
                        </div>
                    )}
                </div>

                {/* Info */}
                <div className="flex flex-col p-8 lg:p-12">
                    <div className="eyebrow mb-3" style={{ color: 'var(--brand-gold)' }}>
                        {product.category?.name ?? 'Product'}
                    </div>
                    <h3 className="font-display text-[34px] leading-[1.05]" style={{ color: 'var(--brand-ink)' }}>
                        {product.name}
                    </h3>
                    <div className="mt-4 flex items-end gap-3">
                        <span className="font-display text-[28px]" style={{ color: 'var(--brand-ink)' }}>
                            ৳ {Number(product.price).toLocaleString()}
                        </span>
                        {hasDiscount && (
                            <span className="mb-1 text-[15px] line-through" style={{ color: 'var(--brand-muted)' }}>
                                ৳ {Number(product.compare_price).toLocaleString()}
                            </span>
                        )}
                    </div>

                    {product.short_description && (
                        <p className="mt-5 text-[14.5px] leading-[1.75]" style={{ color: 'var(--brand-muted)' }}>
                            {product.short_description}
                        </p>
                    )}

                    <div
                        className="mt-6 border-b pb-4"
                        style={{ borderColor: 'var(--brand-line)' }}
                    >
                        <div className="eyebrow mb-1" style={{ color: 'var(--brand-muted)' }}>
                            {product.stock_qty > 0 ? `In Stock (${product.stock_qty} available)` : 'Out of Stock'}
                        </div>
                        {product.sku && (
                            <div className="eyebrow" style={{ color: 'var(--brand-muted)' }}>SKU: {product.sku}</div>
                        )}
                    </div>

                    <button
                        onClick={addToCart}
                        disabled={adding || product.stock_qty <= 0}
                        className="mt-7 h-12 w-full text-[12px] uppercase tracking-[0.2em] font-medium transition disabled:opacity-50 eyebrow"
                        style={{ backgroundColor: added ? 'var(--brand-gold)' : 'var(--brand-slate)', color: '#FBF7EF' }}
                    >
                        {product.has_variant ? 'Select Options' : added ? '✓ Added to Cart' : adding ? 'Adding…' : 'Add to Cart'}
                    </button>

                    <Link
                        href={`/products/${product.slug}`}
                        onClick={onClose}
                        className="mt-4 text-center text-[12px] uppercase tracking-[0.18em] underline-offset-4 hover:underline"
                        style={{ color: 'var(--brand-gold)' }}
                    >
                        View full details →
                    </Link>

                    <div className="mt-auto grid grid-cols-3 gap-4 border-t pt-6" style={{ borderColor: 'rgba(229,221,204,0.5)', marginTop: '2rem' }}>
                        {[
                            { l: 'COD Available', s: 'Pay on delivery' },
                            { l: '7-day returns', s: 'Unworn only' },
                            { l: 'Authentic', s: '100% genuine' },
                        ].map((b, i) => (
                            <div key={i} className="text-center">
                                <div className="text-[12px] font-medium" style={{ color: 'var(--brand-ink)' }}>{b.l}</div>
                                <div className="eyebrow mt-1" style={{ color: 'var(--brand-muted)', fontSize: 9 }}>{b.s}</div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
}

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

function MobileFilterDrawer({
    open,
    onClose,
    filters,
    categories,
    attributes,
    onChange,
    onClear,
    resultCount,
}: {
    open: boolean;
    onClose: () => void;
    filters: FilterState;
    categories: Category[];
    attributes: Attribute[];
    onChange: (updates: Partial<FilterState>) => 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={{ backgroundColor: 'var(--brand-cream)' }}
            >
                <header className="flex items-center justify-between border-b p-5" style={{ borderColor: 'var(--brand-line)' }}>
                    <h3 className="font-display text-[24px]" style={{ color: 'var(--brand-ink)' }}>Filters</h3>
                    <button
                        onClick={onClose}
                        className="flex h-9 w-9 items-center justify-center rounded-full border transition"
                        style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-slate)' }}
                    >
                        <X size={12} />
                    </button>
                </header>
                <div className="flex-1 overflow-auto px-5">
                    <FilterBody filters={filters} categories={categories} attributes={attributes} onChange={onChange} />
                </div>
                <footer className="flex gap-3 border-t p-5" style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-ivory)' }}>
                    <button
                        onClick={onClear}
                        className="flex-1 border py-3.5 text-[12px] uppercase tracking-[0.16em] transition hover:text-gold"
                        style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-ink)' }}
                    >
                        Clear all
                    </button>
                    <button
                        onClick={onClose}
                        className="flex-[1.4] py-3.5 text-[12px] uppercase tracking-[0.16em] font-medium text-white transition hover:opacity-90 eyebrow"
                        style={{ backgroundColor: 'var(--brand-slate)' }}
                    >
                        See {resultCount} products
                    </button>
                </footer>
            </aside>
        </div>
    );
}

// ─── Footer ───────────────────────────────────────────────────────────────────

function PageFooter() {
    const { siteSettings } = usePage<SharedData>().props;
    const s = siteSettings;
    const siteName = s?.site_name ?? 'Kapor Bikreta';
    const logoPath = s?.logo_path;
    const footerDesc = s?.footer_desc ?? '';
    const copyright = (s?.copyright ?? '© {year} All rights reserved.').replace('{year}', String(new Date().getFullYear()));
    const showAbout = s?.show_about ?? true;
    const showBlog = s?.show_blog ?? true;
    const phone = s?.phone ?? '';

    return (
        <footer className="ph-stripe-dark py-14">
            <div className="mx-auto max-w-[1500px] px-5 lg:px-10">
                <div className="grid gap-10 md:grid-cols-4">
                    <div className="md:col-span-2">
                        <Link href="/" className="mb-4 inline-block">
                            {logoPath ? (
                                <img src={`/storage/${logoPath}`} alt={siteName} className="h-9 w-auto brightness-0 invert" />
                            ) : (
                                <span className="font-display text-xl font-medium text-white">{siteName}</span>
                            )}
                        </Link>
                        <p className="mb-5 max-w-xs text-sm leading-relaxed" style={{ color: 'rgba(229,221,204,0.5)' }}>
                            {footerDesc || 'Premium fashion, delivered across Bangladesh with care.'}
                        </p>
                    </div>
                    <div>
                        <p className="eyebrow mb-5 text-white">Quick Links</p>
                        <ul className="space-y-3">
                            {[
                                { href: '/', label: 'Home' },
                                { href: '/products', label: 'All Products' },
                                { href: '/cart', label: 'Cart' },
                                ...(showAbout ? [{ href: '/about', label: 'About Us' }] : []),
                                ...(showBlog ? [{ href: '/blog', label: 'Blog' }] : []),
                            ].map((l) => (
                                <li key={l.href}>
                                    <Link href={l.href} className="link-gold text-sm transition hover:text-white" style={{ color: 'rgba(229,221,204,0.5)' }}>
                                        {l.label}
                                    </Link>
                                </li>
                            ))}
                        </ul>
                    </div>
                    <div>
                        <p className="eyebrow mb-5 text-white">Contact</p>
                        {phone && <p className="mb-2 text-sm" style={{ color: 'rgba(229,221,204,0.5)' }}>{phone}</p>}
                        <p className="text-sm" style={{ color: 'rgba(229,221,204,0.5)' }}>Mon – Sat: 10am – 8pm</p>
                    </div>
                </div>
                <div className="mt-12 border-t pt-6 text-center" style={{ borderColor: 'rgba(229,221,204,0.1)' }}>
                    <p className="eyebrow" style={{ color: 'rgba(229,221,204,0.3)' }}>{copyright}</p>
                </div>
            </div>
        </footer>
    );
}

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

interface Filters {
    search?: string;
    category?: string;
    brand?: string;
    min_price?: string;
    max_price?: string;
    sort?: string;
    attr?: string[] | string;
    availability?: string;
}

function ProductsInner({
    products,
    categories,
    brands: _brands,
    attributes,
    filters,
}: {
    products: PaginatedData<Product>;
    categories: Category[];
    brands: Brand[];
    attributes: Attribute[];
    filters: Filters;
}) {
    const { siteSettings } = usePage<SharedData>().props;

    const activeAttrs: string[] = Array.isArray(filters.attr) ? filters.attr : filters.attr ? [filters.attr] : [];

    const [localFilters, setLocalFilters] = useState<FilterState>({
        search: filters.search ?? '',
        category: filters.category ?? '',
        min_price: filters.min_price ?? '',
        max_price: filters.max_price ?? '',
        sort: filters.sort ?? '',
        attr: activeAttrs,
        availability: filters.availability ?? '',
    });

    const [cols, setCols] = useState(() => {
        try { return Number(localStorage.getItem('collection-cols')) || 3; } catch { return 3; }
    });
    const [wishlist, setWishlist] = useState<Set<number>>(new Set());
    const [quickView, setQuickView] = useState<Product | null>(null);
    const [previewProduct, setPreviewProduct] = useState<Product | null>(null);
    const [mobileFilters, setMobileFilters] = useState(false);
    const priceTimer = useRef<ReturnType<typeof setTimeout>>();

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

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

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

    const clearAll = () => {
        const empty: FilterState = { search: '', category: '', min_price: '', max_price: '', sort: '', attr: [], availability: '' };
        setLocalFilters(empty);
        router.visit('/products');
    };

    const removeFilter = (key: keyof FilterState, value?: string) => {
        if (key === 'attr' && value) {
            navigate({ attr: localFilters.attr.filter((s) => s !== value) });
        } else if (key === 'min_price' || key === 'max_price') {
            navigate({ min_price: '', max_price: '' });
        } else {
            navigate({ [key]: '' });
        }
    };

    const currentCategory = categories.find((c) => c.slug === localFilters.category);
    const siteName = siteSettings?.site_name ?? 'Kapor Bikreta';
    const showAnnouncement = siteSettings?.show_announcement ?? true;
    const announcementText = siteSettings?.announcement_bar ?? '';

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

    return (
        <div style={{ fontFamily: "'Outfit', 'Instrument Sans', sans-serif", backgroundColor: 'var(--brand-cream)' }}>
            <Head title={currentCategory ? `${currentCategory.name} — ${siteName}` : `All Products — ${siteName}`} />

            {/* Announcement bar */}
            {showAnnouncement && announcementText && (
                <div className="ph-stripe-dark overflow-hidden py-2.5">
                    <div className="marquee-track">
                        {[...Array(8)].map((_, i) => (
                            <span key={i} className="eyebrow flex items-center px-8" style={{ color: 'rgba(229,221,204,0.55)' }}>
                                <span className="mr-3 text-xs" style={{ color: 'var(--brand-gold)' }}>♦</span>
                                {announcementText}
                            </span>
                        ))}
                    </div>
                </div>
            )}

            <SiteHeader activePage="products" />
            <CollectionHero
                count={products.total}
                total={products.total}
                categoryName={currentCategory?.name}
            />

            <main className="mx-auto max-w-[1500px] px-5 py-10 lg:px-10 lg:py-14">
                <div className="grid gap-10 lg:grid-cols-[280px_1fr] lg:gap-14">
                    {/* Desktop filter sidebar */}
                    <aside className="hidden lg:block">
                        <div className="sticky top-[94px]">
                            <div
                                className="flex items-center gap-3 border-b pb-5"
                                style={{ borderColor: 'var(--brand-line)' }}
                            >
                                <DiamondGlyph size={14} stroke="var(--brand-gold)" />
                                <h2 className="font-display text-[24px] leading-none" style={{ color: 'var(--brand-ink)' }}>
                                    Refine
                                </h2>
                            </div>
                            <FilterBody
                                filters={localFilters}
                                categories={categories}
                                attributes={attributes}
                                onChange={handleFilterChange}
                            />
                            <button
                                onClick={clearAll}
                                className="mt-5 w-full border py-3 text-[12px] uppercase tracking-[0.16em] transition hover:text-gold"
                                style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-muted)' }}
                            >
                                Clear all filters
                            </button>
                        </div>
                    </aside>

                    {/* Product grid */}
                    <section>
                        <ActiveFilters
                            filters={localFilters}
                            categories={categories}
                            attributes={attributes}
                            onRemove={removeFilter}
                            onClear={clearAll}
                        />
                        <SortBar
                            count={products.total}
                            sort={localFilters.sort}
                            onSort={(v) => navigate({ sort: v })}
                            cols={cols}
                            onCols={(n) => { setCols(n); try { localStorage.setItem('collection-cols', String(n)); } catch {} }}
                            onMobileFilters={() => setMobileFilters(true)}
                        />

                        {products.data.length === 0 ? (
                            <div className="flex flex-col items-center justify-center py-32 text-center">
                                <div
                                    className="mb-6 flex h-20 w-20 items-center justify-center rounded-full border"
                                    style={{ borderColor: 'var(--brand-line)' }}
                                >
                                    <DiamondGlyph size={28} stroke="var(--brand-gold)" />
                                </div>
                                <h3 className="font-display text-[36px] leading-tight" style={{ color: 'var(--brand-ink)' }}>
                                    Nothing matches yet.
                                </h3>
                                <p className="mx-auto mt-3 max-w-[380px]" style={{ color: 'var(--brand-muted)' }}>
                                    Try widening your filters or browse the full collection.
                                </p>
                                <button
                                    onClick={clearAll}
                                    className="mt-7 px-7 py-3.5 text-[12px] uppercase tracking-[0.18em] text-white transition hover:opacity-90 eyebrow"
                                    style={{ backgroundColor: 'var(--brand-slate)' }}
                                >
                                    Reset filters
                                </button>
                            </div>
                        ) : (
                            <>
                                <div className={`mt-10 grid ${gridClass} gap-x-5 gap-y-12 lg:gap-x-8 lg:gap-y-16`}>
                                    {products.data.map((p) => (
                                        <ProductCard
                                            key={p.id}
                                            product={p}
                                            wished={wishlist.has(p.id)}
                                            onWish={(id) => {
                                                const next = new Set(wishlist);
                                                next.has(id) ? next.delete(id) : next.add(id);
                                                setWishlist(next);
                                            }}
                                            onQuickView={setQuickView}
                                            onPreview={setPreviewProduct}
                                        />
                                    ))}
                                </div>

                                {/* Pagination */}
                                {products.last_page > 1 && (
                                    <div
                                        className="mt-20 flex flex-col items-center justify-between gap-4 border-t pt-10 sm:flex-row"
                                        style={{ borderColor: 'var(--brand-line)' }}
                                    >
                                        <div className="eyebrow" style={{ color: 'var(--brand-muted)' }}>
                                            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={{
                                                        backgroundColor: link.active ? 'var(--brand-slate)' : 'transparent',
                                                        borderColor: link.active ? 'var(--brand-slate)' : 'var(--brand-line)',
                                                        color: link.active ? '#FBF7EF' : 'var(--brand-ink)',
                                                    }}
                                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                                />
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </>
                        )}
                    </section>
                </div>
            </main>

            <PageFooter />

            {/* Overlays */}
            <FabricPreviewModal product={previewProduct} onClose={() => setPreviewProduct(null)} />
            <QuickViewModal product={quickView} onClose={() => setQuickView(null)} />
            <MobileFilterDrawer
                open={mobileFilters}
                onClose={() => setMobileFilters(false)}
                filters={localFilters}
                categories={categories}
                attributes={attributes}
                onChange={handleFilterChange}
                onClear={clearAll}
                resultCount={products.total}
            />
        </div>
    );
}

export default function ProductsIndex(props: {
    products: PaginatedData<Product>;
    categories: Category[];
    brands: Brand[];
    attributes: Attribute[];
    filters: Filters;
}) {
    return (
        <LangProvider>
            <ProductsInner {...props} />
        </LangProvider>
    );
}
