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

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

// ─── Diamond Glyph ────────────────────────────────────────────────────────────

function DiamondGlyph({ size = 48, className = '', style }: { size?: number; className?: string; style?: React.CSSProperties }) {
    return (
        <svg width={size} height={size} viewBox="0 0 48 48" fill="none" className={className} style={style}>
            <path d="M24 3L45 24L24 45L3 24Z" stroke="currentColor" strokeWidth="1.5" />
            <path d="M24 10.5L37.5 24L24 37.5L10.5 24Z" stroke="currentColor" strokeWidth="1" />
            <text
                x="24"
                y="28"
                textAnchor="middle"
                fontSize="10"
                fontFamily="Cormorant Garamond, Georgia, serif"
                fill="currentColor"
                fontWeight="500"
            >
                ◆
            </text>
        </svg>
    );
}

// ─── Announcement Bar ─────────────────────────────────────────────────────────

function AnnouncementBar({ text }: { text: string }) {
    const phrases = text
        ? [text]
        : ['নতুন কালেকশন এসেছে', 'FREE SHIPPING OVER ৳2,000', 'COD AVAILABLE NATIONWIDE', '১০০% অথেন্টিক পণ্য'];
    const repeated = [...phrases, ...phrases, ...phrases, ...phrases];

    return (
        <div className="ph-stripe-dark overflow-hidden py-2.5">
            <div className="marquee-track">
                {repeated.map((phrase, 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>
                        {phrase}
                    </span>
                ))}
            </div>
        </div>
    );
}

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

function Hero({ banners }: { banners: Banner[] }) {
    const { siteSettings } = usePage<SharedData>().props;
    const [current, setCurrent] = useState(0);
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

    const tagline = siteSettings?.tagline ?? '';

    useEffect(() => {
        if (banners.length < 2) return;
        timerRef.current = setInterval(() => setCurrent((c) => (c + 1) % banners.length), 5500);
        return () => {
            if (timerRef.current) clearInterval(timerRef.current);
        };
    }, [banners.length]);

    const active = banners[current];

    return (
        <section className="ph-stripe overflow-hidden">
            <div className="mx-auto max-w-[1400px] px-6 py-16 lg:px-10 lg:py-24">
                <div className="grid items-center gap-10 lg:grid-cols-[1fr_420px]">
                    {/* Left: editorial text */}
                    <div>
                        <p className="eyebrow mb-5" style={{ color: 'var(--brand-gold)' }}>
                            ♦ {tagline || 'নতুন সিজন কালেকশন'}
                        </p>
                        <h1
                            className="font-display mb-6 text-5xl font-medium leading-[1.1] md:text-6xl lg:text-7xl"
                            style={{ color: 'var(--brand-ink)' }}
                        >
                            {active?.title ?? 'আপনার স্টাইলের'}
                            <br />
                            <em className="not-italic" style={{ color: 'var(--brand-gold)' }}>
                                {active?.subtitle ?? 'নতুন সংগ্রহ'}
                            </em>
                        </h1>
                        <p className="mb-8 max-w-sm text-base leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                            হস্তনির্মিত পাঞ্জাবি থেকে ডিজাইনার কালেকশন — প্রতিটি পোশাক তৈরি হয় আপনার জন্য, আপনার মুহূর্তের জন্য।
                        </p>
                        <div className="flex flex-wrap gap-3">
                            <Link
                                href="/products"
                                className="inline-block px-9 py-3 text-white transition-opacity hover:opacity-85"
                                style={{ backgroundColor: 'var(--brand-slate)' }}
                            >
                                <span className="eyebrow">এখনই কিনুন</span>
                            </Link>
                            <Link
                                href="/products"
                                className="inline-block border px-9 py-3 transition hover:bg-[var(--brand-slate)] hover:text-white"
                                style={{ borderColor: 'var(--brand-slate)', color: 'var(--brand-slate)' }}
                            >
                                <span className="eyebrow">সব দেখুন</span>
                            </Link>
                        </div>

                        {/* Stats strip */}
                        <div
                            className="mt-10 grid grid-cols-4 gap-4 border-t pt-8"
                            style={{ borderColor: 'var(--brand-line)' }}
                        >
                            {[
                                ['10K+', 'Customers'],
                                ['500+', 'Products'],
                                ['64', 'Districts'],
                                ['24/7', 'Support'],
                            ].map(([num, label]) => (
                                <div key={label}>
                                    <div
                                        className="font-display text-2xl font-semibold"
                                        style={{ color: 'var(--brand-slate)' }}
                                    >
                                        {num}
                                    </div>
                                    <div className="eyebrow mt-0.5" style={{ color: 'var(--brand-muted)' }}>
                                        {label}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Right: image */}
                    <div className="relative hidden lg:block">
                        {active ? (
                            <div className="relative overflow-hidden" style={{ aspectRatio: '4/5' }}>
                                <img
                                    src={`/storage/${active.image}`}
                                    alt={active.title ?? 'Hero'}
                                    className="h-full w-full object-cover transition-transform duration-700 hover:scale-[1.03]"
                                />
                                {/* Overlay card */}
                                <div
                                    className="absolute bottom-5 left-5 right-5 border p-4"
                                    style={{
                                        backgroundColor: 'rgba(31,42,48,0.84)',
                                        borderColor: 'rgba(184,137,63,0.45)',
                                        backdropFilter: 'blur(6px)',
                                    }}
                                >
                                    <p className="eyebrow mb-1" style={{ color: 'var(--brand-gold)' }}>
                                        নতুন কালেকশন
                                    </p>
                                    <p className="font-display text-lg text-white">{active.title ?? 'Season Collection'}</p>
                                </div>
                            </div>
                        ) : (
                            <div
                                className="flex items-center justify-center"
                                style={{ aspectRatio: '4/5', backgroundColor: 'var(--brand-line)' }}
                            >
                                <DiamondGlyph size={72} style={{ color: 'var(--brand-slate)', opacity: 0.25 }} />
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Banner dots */}
            {banners.length > 1 && (
                <div className="flex justify-center gap-2 pb-6">
                    {banners.map((_, i) => (
                        <button
                            key={i}
                            onClick={() => setCurrent(i)}
                            className="h-1.5 transition-all duration-300"
                            style={{
                                width: i === current ? '24px' : '8px',
                                borderRadius: '2px',
                                backgroundColor: i === current ? 'var(--brand-gold)' : 'var(--brand-line)',
                            }}
                        />
                    ))}
                </div>
            )}
        </section>
    );
}

// ─── Category Marquee ─────────────────────────────────────────────────────────

function CategoryMarquee({ categories }: { categories: Category[] }) {
    if (!categories.length) return null;
    const names = categories.map((c) => c.name);
    const repeated = [...names, ...names, ...names, ...names];

    return (
        <div className="ph-stripe-dark overflow-hidden py-5 select-none">
            <div className="marquee-track" style={{ animationDuration: '22s' }}>
                {repeated.map((name, i) => (
                    <span key={i} className="font-display mx-4 text-2xl italic" style={{ color: 'rgba(229,221,204,0.35)' }}>
                        {name}
                        <span className="mx-6 text-sm not-italic" style={{ color: 'var(--brand-gold)' }}>
                            ◆
                        </span>
                    </span>
                ))}
            </div>
        </div>
    );
}

// ─── Collections ─────────────────────────────────────────────────────────────

function Collections({ categories }: { categories: Category[] }) {
    const display = categories.slice(0, 4);
    if (!display.length) return null;

    return (
        <section className="py-16" style={{ backgroundColor: 'var(--brand-ivory)' }}>
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                <div className="mb-10 text-center">
                    <p className="eyebrow mb-2" style={{ color: 'var(--brand-gold)' }}>
                        ♦ Shop by Category
                    </p>
                    <h2 className="font-display text-3xl font-medium md:text-4xl" style={{ color: 'var(--brand-ink)' }}>
                        Our Collections
                    </h2>
                </div>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    {display.map((cat) => (
                        <Link
                            key={cat.id}
                            href={`/products?category=${cat.slug}`}
                            className="card-lift group relative block overflow-hidden"
                            style={{ aspectRatio: '3/4' }}
                        >
                            {cat.image ? (
                                <img
                                    src={`/storage/${cat.image}`}
                                    alt={cat.name}
                                    className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                                />
                            ) : (
                                <div
                                    className="flex h-full w-full items-center justify-center"
                                    style={{ backgroundColor: 'var(--brand-line)' }}
                                >
                                    <DiamondGlyph size={48} style={{ color: 'var(--brand-slate)', opacity: 0.2 }} />
                                </div>
                            )}
                            <div
                                className="absolute inset-0 flex flex-col justify-end p-5"
                                style={{ background: 'linear-gradient(to top, rgba(31,42,48,0.82) 0%, transparent 55%)' }}
                            >
                                <p className="font-display text-xl font-medium text-white">{cat.name}</p>
                                <p className="eyebrow mt-1" style={{ color: 'var(--brand-gold)' }}>
                                    Shop →
                                </p>
                            </div>
                        </Link>
                    ))}
                </div>

                {categories.length > 4 && (
                    <div className="mt-8 text-center">
                        <Link href="/products" className="link-gold eyebrow" style={{ color: 'var(--brand-slate)' }}>
                            View all categories →
                        </Link>
                    </div>
                )}
            </div>
        </section>
    );
}

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

function ProductCard({
    product,
    wished,
    onWish,
    onPreview,
}: {
    product: Product;
    wished: boolean;
    onWish: (id: number) => 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) {
            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} style={{ color: '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>
                    <button
                        onClick={(e) => { e.preventDefault(); e.stopPropagation(); onWish(product.id); }}
                        className="pointer-events-auto 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>
                </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 preview button */}
            <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>
    );
}

// ─── Featured Products ────────────────────────────────────────────────────────

function FeaturedProducts({
    featuredProducts,
    newArrivals,
    bestSellers,
    trendingProducts,
}: {
    featuredProducts: Product[];
    newArrivals: Product[];
    bestSellers: Product[];
    trendingProducts: Product[];
}) {
    const tabs = [
        { key: 'featured', label: 'Featured', products: featuredProducts },
        { key: 'new', label: 'New Arrivals', products: newArrivals },
        { key: 'best', label: 'Best Sellers', products: bestSellers },
        { key: 'trending', label: 'Trending', products: trendingProducts },
    ].filter((t) => t.products.length > 0);

    const [activeKey, setActiveKey] = useState(tabs[0]?.key ?? 'featured');
    const [wishlist, setWishlist] = useState<Set<number>>(new Set());
    const [previewProduct, setPreviewProduct] = useState<Product | null>(null);
    const active = tabs.find((t) => t.key === activeKey) ?? tabs[0];

    const toggleWish = (id: number) =>
        setWishlist((prev) => {
            const next = new Set(prev);
            next.has(id) ? next.delete(id) : next.add(id);
            return next;
        });

    if (!tabs.length) return null;

    return (
        <section className="ph-stripe py-16">
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                {/* Section header */}
                <div className="mb-8 flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
                    <div>
                        <p className="eyebrow mb-2" style={{ color: 'var(--brand-gold)' }}>
                            ♦ Curated For You
                        </p>
                        <h2 className="font-display text-3xl font-medium md:text-4xl" style={{ color: 'var(--brand-ink)' }}>
                            Our Products
                        </h2>
                    </div>

                    {/* Tabs */}
                    <div className="flex gap-1 border-b" style={{ borderColor: 'var(--brand-line)' }}>
                        {tabs.map((tab) => (
                            <button
                                key={tab.key}
                                onClick={() => setActiveKey(tab.key)}
                                className="eyebrow px-3 pb-3 transition-colors"
                                style={{
                                    color: activeKey === tab.key ? 'var(--brand-slate)' : 'var(--brand-muted)',
                                    borderBottom: activeKey === tab.key ? '2px solid var(--brand-gold)' : '2px solid transparent',
                                    marginBottom: '-1px',
                                }}
                            >
                                {tab.label}
                            </button>
                        ))}
                    </div>
                </div>

                {/* Grid */}
                <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
                    {(active?.products ?? []).slice(0, 8).map((p) => (
                        <ProductCard
                            key={p.id}
                            product={p}
                            wished={wishlist.has(p.id)}
                            onWish={toggleWish}
                            onPreview={setPreviewProduct}
                        />
                    ))}
                </div>

                <div className="mt-10 text-center">
                    <Link
                        href="/products"
                        className="inline-block border px-10 py-3 transition hover:opacity-80"
                        style={{ borderColor: 'var(--brand-slate)', color: 'var(--brand-slate)' }}
                    >
                        <span className="eyebrow">View All Products</span>
                    </Link>
                </div>
            </div>

            <FabricPreviewModal product={previewProduct} onClose={() => setPreviewProduct(null)} />
        </section>
    );
}

// ─── Brand Story ──────────────────────────────────────────────────────────────

function BrandStory() {
    return (
        <section className="py-16" style={{ backgroundColor: 'var(--brand-ivory)' }}>
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                <div className="grid items-center gap-12 lg:grid-cols-2">
                    {/* Image collage */}
                    <div className="relative hidden h-[500px] lg:block">
                        <div
                            className="absolute left-0 top-0 h-72 w-48 rounded-sm"
                            style={{ backgroundColor: 'var(--brand-line)' }}
                        />
                        <div
                            className="absolute bottom-0 right-4 h-64 w-52 rounded-sm border-4"
                            style={{ backgroundColor: 'var(--brand-cream)', borderColor: 'var(--brand-ivory)' }}
                        />
                        <div
                            className="absolute left-16 top-20 h-56 w-40 overflow-hidden rounded-sm"
                            style={{ backgroundColor: 'var(--brand-line)' }}
                        >
                            <div
                                className="h-full w-full"
                                style={{
                                    background:
                                        'linear-gradient(135deg, var(--brand-cream) 0%, var(--brand-line) 100%)',
                                }}
                            />
                        </div>
                        {/* Brand mark */}
                        <div
                            className="absolute right-16 top-32 flex h-16 w-16 items-center justify-center rounded-full border-2"
                            style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-gold)' }}
                        >
                            <DiamondGlyph size={32} style={{ color: 'var(--brand-gold)' }} />
                        </div>
                    </div>

                    {/* Text */}
                    <div>
                        <p className="eyebrow mb-4" style={{ color: 'var(--brand-gold)' }}>
                            ♦ Our Story
                        </p>
                        <h2
                            className="font-display mb-6 text-3xl font-medium leading-snug md:text-4xl"
                            style={{ color: 'var(--brand-ink)' }}
                        >
                            যত্ন দিয়ে তৈরি,
                            <br />
                            <span className="italic" style={{ color: 'var(--brand-gold)' }}>
                                আপনার জন্য বানানো
                            </span>
                        </h2>
                        <p className="mb-5 leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                            আমরা বিশ্বাস করি প্রতিটি মানুষ সেরা পোশাক পাওয়ার অধিকারী। আমাদের সংগ্রহ তৈরি হয়
                            সর্বোচ্চ মানের কাপড় থেকে, দক্ষ কারিগরদের হাতে — প্রতিটি সেলাইয়ে আমাদের
                            প্রতিশ্রুতি।
                        </p>
                        <p className="mb-8 leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                            ২০১৮ সাল থেকে আমরা বাংলাদেশের হাজার হাজার পরিবারের বিশ্বস্ত পোশাক ব্র্যান্ড। ঈদ
                            থেকে রোজকার পোশাক — প্রতিটি অনুষ্ঠানের জন্য আমাদের সংগ্রহ আপনার পাশে।
                        </p>
                        <div
                            className="grid grid-cols-3 gap-4 border-t pt-8"
                            style={{ borderColor: 'var(--brand-line)' }}
                        >
                            {[
                                ['২০১৮', 'সাল থেকে'],
                                ['৫০০+', 'ডিজাইন'],
                                ['১০০%', 'অথেন্টিক'],
                            ].map(([num, label]) => (
                                <div key={label} className="text-center">
                                    <div
                                        className="font-display text-2xl font-semibold"
                                        style={{ color: 'var(--brand-gold)' }}
                                    >
                                        {num}
                                    </div>
                                    <div className="eyebrow mt-1" style={{ color: 'var(--brand-muted)' }}>
                                        {label}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
}

// ─── Trust Badges ─────────────────────────────────────────────────────────────

function TrustBadges() {
    const badges = [
        { icon: '🚚', title: 'Free Delivery', desc: 'Orders over ৳2,000' },
        { icon: '💵', title: 'Cash on Delivery', desc: 'Pay when it arrives' },
        { icon: '↩', title: '7-Day Returns', desc: 'Hassle-free policy' },
        { icon: '✦', title: '100% Authentic', desc: 'Quality guaranteed' },
    ];

    return (
        <section className="ph-stripe py-12">
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                <div className="grid grid-cols-2 gap-6 lg:grid-cols-4">
                    {badges.map((b) => (
                        <div key={b.title} className="flex items-start gap-4">
                            <span className="mt-0.5 text-2xl leading-none">{b.icon}</span>
                            <div>
                                <p className="eyebrow mb-0.5" style={{ color: 'var(--brand-slate)' }}>
                                    {b.title}
                                </p>
                                <p className="text-sm" style={{ color: 'var(--brand-muted)' }}>
                                    {b.desc}
                                </p>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}

// ─── Eid Banner ───────────────────────────────────────────────────────────────

function EidBanner() {
    return (
        <section className="py-20 text-center" style={{ backgroundColor: 'var(--brand-slate)' }}>
            <div className="mx-auto max-w-2xl px-6">
                <DiamondGlyph
                    size={40}
                    className="mx-auto mb-6"
                    style={{ color: 'var(--brand-gold)' }}
                />
                <p className="eyebrow mb-3" style={{ color: 'var(--brand-gold)' }}>
                    Special Collection
                </p>
                <h2 className="font-display mb-4 text-4xl font-medium text-white md:text-5xl">
                    ঈদ কালেকশন এসে গেছে
                </h2>
                <p className="mb-8 leading-relaxed" style={{ color: 'rgba(229,221,204,0.65)' }}>
                    এই ঈদে আপনার প্রিয়জনের জন্য নিয়ে যান সেরা পাঞ্জাবি। বিশেষ ছাড়ে পাচ্ছেন আমাদের
                    সীমিত ইডিশন কালেকশন।
                </p>
                <Link
                    href="/products"
                    className="inline-block border px-10 py-3.5 text-white transition hover:bg-[var(--brand-gold)] hover:border-[var(--brand-gold)]"
                    style={{ borderColor: 'var(--brand-gold)' }}
                >
                    <span className="eyebrow" style={{ color: 'inherit' }}>
                        Shop Eid Collection
                    </span>
                </Link>
            </div>
        </section>
    );
}

// ─── Testimonials ─────────────────────────────────────────────────────────────

function Testimonials() {
    const reviews = [
        {
            name: 'রাফি আহমেদ',
            location: 'ঢাকা',
            text: 'কাপড়ের মান অসাধারণ! ডেলিভারি সময়মতো এসেছে। পরের বারও এখান থেকেই কিনব।',
            stars: 5,
        },
        {
            name: 'সাইফুল ইসলাম',
            location: 'চট্টগ্রাম',
            text: 'ঈদের জন্য পাঞ্জাবি কিনলাম, সবাই প্রশংসা করেছে। দাম অনুযায়ী মান অনেক ভালো।',
            stars: 5,
        },
        {
            name: 'তানভীর হাসান',
            location: 'সিলেট',
            text: 'অনলাইনে দেখে যা মনে হয়েছিল তার চেয়ে বাস্তবে আরও সুন্দর। রিটার্ন পলিসিও ভালো।',
            stars: 5,
        },
    ];

    return (
        <section className="py-16" style={{ backgroundColor: 'var(--brand-ivory)' }}>
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                <div className="mb-10 text-center">
                    <p className="eyebrow mb-2" style={{ color: 'var(--brand-gold)' }}>
                        ♦ Customer Reviews
                    </p>
                    <h2 className="font-display text-3xl font-medium md:text-4xl" style={{ color: 'var(--brand-ink)' }}>
                        What They Say
                    </h2>
                </div>

                <div className="grid gap-5 md:grid-cols-3">
                    {reviews.map((r, i) => (
                        <div
                            key={i}
                            className="border p-6"
                            style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-cream)' }}
                        >
                            <div className="mb-4 flex gap-0.5">
                                {Array.from({ length: r.stars }).map((_, s) => (
                                    <span key={s} style={{ color: 'var(--brand-gold)' }}>
                                        ★
                                    </span>
                                ))}
                            </div>
                            <p className="mb-5 italic leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                                "{r.text}"
                            </p>
                            <div className="flex items-center gap-3">
                                <div
                                    className="flex h-9 w-9 items-center justify-center rounded-full text-xs font-semibold text-white"
                                    style={{ backgroundColor: 'var(--brand-slate)' }}
                                >
                                    {r.name[0]}
                                </div>
                                <div>
                                    <p className="text-sm font-medium" style={{ color: 'var(--brand-ink)' }}>
                                        {r.name}
                                    </p>
                                    <p className="eyebrow" style={{ color: 'var(--brand-muted)' }}>
                                        {r.location}
                                    </p>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}

// ─── FAQ ──────────────────────────────────────────────────────────────────────

function FAQ() {
    const faqs = [
        { q: 'ডেলিভারি কতদিনে হয়?', a: 'ঢাকার ভেতরে ১–২ কার্যদিবস, ঢাকার বাইরে ৩–৫ কার্যদিবসের মধ্যে ডেলিভারি পাবেন।' },
        { q: 'Cash on Delivery কি পাওয়া যায়?', a: 'হ্যাঁ, সারাদেশে (৬৪ জেলায়) Cash on Delivery সুবিধা পাওয়া যায়।' },
        {
            q: 'পণ্য রিটার্ন করতে পারব?',
            a: 'পণ্য পাওয়ার ৭ দিনের মধ্যে রিটার্ন করা যাবে। শুধুমাত্র অব্যবহৃত ও অক্ষত অবস্থায় রিটার্ন গ্রহণযোগ্য।',
        },
        {
            q: 'সাইজ কিভাবে বুঝব?',
            a: 'প্রতিটি পণ্যের পাশে সাইজ চার্ট দেওয়া আছে। প্রশ্ন থাকলে আমাদের হোয়াটসঅ্যাপে যোগাযোগ করুন।',
        },
        {
            q: 'পেমেন্ট কীভাবে করব?',
            a: 'Cash on Delivery ছাড়াও bKash, Nagad, Rocket এবং কার্ড পেমেন্ট গ্রহণ করা হয়।',
        },
    ];

    const [open, setOpen] = useState<number | null>(null);

    return (
        <section className="ph-stripe py-16">
            <div className="mx-auto max-w-2xl px-6">
                <div className="mb-10 text-center">
                    <p className="eyebrow mb-2" style={{ color: 'var(--brand-gold)' }}>
                        ♦ Common Questions
                    </p>
                    <h2 className="font-display text-3xl font-medium md:text-4xl" style={{ color: 'var(--brand-ink)' }}>
                        FAQ
                    </h2>
                </div>

                <div>
                    {faqs.map((faq, i) => (
                        <div key={i} className="border-b" style={{ borderColor: 'var(--brand-line)' }}>
                            <button
                                onClick={() => setOpen(open === i ? null : i)}
                                className="flex w-full items-center justify-between py-4 text-left"
                            >
                                <span className="font-medium" style={{ color: 'var(--brand-ink)' }}>
                                    {faq.q}
                                </span>
                                <span
                                    className="ml-4 flex-shrink-0 text-xl leading-none transition-transform duration-200"
                                    style={{
                                        color: 'var(--brand-gold)',
                                        transform: open === i ? 'rotate(45deg)' : 'rotate(0deg)',
                                    }}
                                >
                                    +
                                </span>
                            </button>
                            {open === i && (
                                <p className="pb-4 leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                                    {faq.a}
                                </p>
                            )}
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}

// ─── Newsletter ───────────────────────────────────────────────────────────────

function Newsletter() {
    const [email, setEmail] = useState('');
    const [sent, setSent] = useState(false);

    return (
        <section className="ph-stripe-dark py-20 text-center">
            <div className="mx-auto max-w-xl px-6">
                <DiamondGlyph size={36} className="mx-auto mb-6" style={{ color: 'var(--brand-gold)' }} />
                <p className="eyebrow mb-3" style={{ color: 'var(--brand-gold)' }}>
                    Stay Updated
                </p>
                <h2 className="font-display mb-4 text-3xl font-medium text-white md:text-4xl">
                    Exclusive Offers First
                </h2>
                <p className="mb-8" style={{ color: 'rgba(229,221,204,0.55)' }}>
                    নতুন কালেকশন এবং বিশেষ অফার সম্পর্কে সবার আগে জানতে সাবস্ক্রাইব করুন।
                </p>

                {sent ? (
                    <p className="eyebrow py-3" style={{ color: 'var(--brand-gold)' }}>
                        ✓ Subscribed! Thank you.
                    </p>
                ) : (
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            if (email.trim()) setSent(true);
                        }}
                        className="flex"
                    >
                        <input
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            placeholder="your@email.com"
                            required
                            className="flex-1 bg-transparent px-4 py-3 text-white placeholder-slate-600 focus:outline-none"
                            style={{ border: '1px solid rgba(229,221,204,0.25)' }}
                        />
                        <button
                            type="submit"
                            className="px-7 py-3 text-white transition-opacity hover:opacity-90 eyebrow flex-shrink-0"
                            style={{ backgroundColor: 'var(--brand-gold)' }}
                        >
                            Subscribe
                        </button>
                    </form>
                )}
            </div>
        </section>
    );
}

// ─── 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 ?? '';

    const links = [
        { href: '/', label: 'Home' },
        { href: '/products', label: 'Products' },
        { href: '/cart', label: 'Cart' },
        ...(showAbout ? [{ href: '/about', label: 'About Us' }] : []),
        ...(showBlog ? [{ href: '/blog', label: 'Blog' }] : []),
    ];

    return (
        <footer className="ph-stripe-dark py-14">
            <div className="mx-auto max-w-[1400px] px-6 lg:px-10">
                <div className="grid gap-10 md:grid-cols-4">
                    {/* Brand */}
                    <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 panjabi and fashion wear, delivered across Bangladesh with care.'}
                        </p>
                        <div className="flex gap-5">
                            {s?.facebook && (
                                <a
                                    href={s.facebook}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="eyebrow transition hover:text-white"
                                    style={{ color: 'rgba(229,221,204,0.4)' }}
                                >
                                    FB
                                </a>
                            )}
                            {s?.instagram && (
                                <a
                                    href={s.instagram}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="eyebrow transition hover:text-white"
                                    style={{ color: 'rgba(229,221,204,0.4)' }}
                                >
                                    IG
                                </a>
                            )}
                            {s?.youtube && (
                                <a
                                    href={s.youtube}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="eyebrow transition hover:text-white"
                                    style={{ color: 'rgba(229,221,204,0.4)' }}
                                >
                                    YT
                                </a>
                            )}
                        </div>
                    </div>

                    {/* Quick Links */}
                    <div>
                        <p className="eyebrow mb-5 text-white">Quick Links</p>
                        <ul className="space-y-3">
                            {links.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>

                    {/* Contact */}
                    <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>
                        <p className="mt-1 text-sm" style={{ color: 'rgba(229,221,204,0.5)' }}>
                            Available nationwide
                        </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 Inner ───────────────────────────────────────────────────────────────

function HomeInner({
    banners,
    categories,
    featuredProducts,
    newArrivals,
    bestSellers,
    trendingProducts,
}: {
    banners: Banner[];
    categories: Category[];
    featuredProducts: Product[];
    newArrivals: Product[];
    bestSellers: Product[];
    trendingProducts: Product[];
}) {
    const { siteSettings } = usePage<SharedData>().props;
    const siteName = siteSettings?.site_name ?? 'Kapor Bikreta';
    const tagline = siteSettings?.tagline ?? '';
    const showAnnouncement = siteSettings?.show_announcement ?? true;
    const announcementText = siteSettings?.announcement_bar ?? '';

    return (
        <div style={{ fontFamily: "'Outfit', 'Instrument Sans', sans-serif", backgroundColor: 'var(--brand-ivory)' }}>
            <Head title={`${siteName}${tagline ? ` — ${tagline}` : ' — Premium Fashion'}`} />

            {showAnnouncement && <AnnouncementBar text={announcementText} />}
            <SiteHeader activePage="home" />
            <Hero banners={banners} />
            <CategoryMarquee categories={categories} />
            <Collections categories={categories} />
            <FeaturedProducts
                featuredProducts={featuredProducts}
                newArrivals={newArrivals}
                bestSellers={bestSellers}
                trendingProducts={trendingProducts}
            />
            <BrandStory />
            <TrustBadges />
            <EidBanner />
            <Testimonials />
            <FAQ />
            <Newsletter />
            <PageFooter />
        </div>
    );
}

// ─── Export ───────────────────────────────────────────────────────────────────

export default function HomePage(props: {
    banners: Banner[];
    categories: Category[];
    featuredProducts: Product[];
    newArrivals: Product[];
    bestSellers: Product[];
    trendingProducts: Product[];
}) {
    return (
        <LangProvider>
            <HomeInner {...props} />
        </LangProvider>
    );
}
