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

import SiteHeader from '@/components/site-header';
import { LangProvider } from '@/lib/lang';
import { type PaginatedData, type SharedData } from '@/types';

// ─── Interfaces ───────────────────────────────────────────────────────────────

interface BlogCategory {
    id: number;
    name: string;
    slug: string;
}

interface BlogPost {
    id: number;
    title: string;
    slug: string;
    thumbnail: string | null;
    excerpt: string | null;
    created_at: string;
    category: BlogCategory | null;
}

interface Props {
    posts: PaginatedData<BlogPost>;
    categories: BlogCategory[];
    filters: { category?: string; search?: string };
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function readTime(post: BlogPost): number {
    return Math.max(2, Math.ceil(((post.excerpt?.length ?? 0) + post.title.length) / 100));
}

function formatDate(iso: string): string {
    return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}

// ─── 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>
    );
}

function SectionEyebrow({ children, tone = 'gold' }: { children: React.ReactNode; tone?: 'gold' | 'ivory' }) {
    return (
        <div
            className="eyebrow mb-5 flex items-center gap-3"
            style={{ color: tone === 'ivory' ? 'rgba(251,247,239,0.55)' : 'var(--brand-gold-dim, var(--brand-gold))' }}
        >
            <DiamondGlyph size={10} stroke="var(--brand-gold)" />
            {children}
        </div>
    );
}

function Placeholder({ label, dark = false, ratio = '4/5', className = '' }: { label?: string; dark?: boolean; ratio?: string; className?: string }) {
    return (
        <div
            className={`relative w-full overflow-hidden ${dark ? 'ph-stripe-dark' : 'ph-stripe'} ${className}`}
            style={{ aspectRatio: ratio }}
        >
            <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
                <DiamondGlyph size={28} stroke={dark ? 'rgba(184,137,63,0.4)' : 'rgba(184,137,63,0.35)'} />
                {label && (
                    <span
                        className="eyebrow px-4 text-center leading-relaxed"
                        style={{ color: dark ? 'rgba(229,221,204,0.4)' : 'rgba(111,107,98,0.7)', fontSize: '9px' }}
                    >
                        {label}
                    </span>
                )}
            </div>
        </div>
    );
}

function PostImage({ post, ratio = '4/5', dark = false }: { post: BlogPost; ratio?: string; dark?: boolean }) {
    if (post.thumbnail) {
        return (
            <div className="relative w-full overflow-hidden" style={{ aspectRatio: ratio }}>
                <img
                    src={`/storage/${post.thumbnail}`}
                    alt={post.title}
                    className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.04]"
                />
            </div>
        );
    }
    return <Placeholder label={`journal · ${post.slug}`} dark={dark} ratio={ratio} />;
}

// ─── Arrow Icon ───────────────────────────────────────────────────────────────

function ArrowIcon({ size = 14 }: { size?: number }) {
    return (
        <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
            <path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    );
}

// ─── Blog Hero ────────────────────────────────────────────────────────────────

function BlogHero({ query, setQuery, onSearch }: { query: string; setQuery: (v: string) => void; onSearch: () => void }) {
    return (
        <section
            className="ornament-bg relative overflow-hidden border-b"
            style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}
        >
            <div className="pointer-events-none absolute -right-20 -top-20 hidden opacity-15 lg:block">
                <DiamondGlyph size={400} stroke="var(--brand-gold)" />
            </div>
            <div className="pointer-events-none absolute -bottom-16 -left-12 hidden opacity-10 lg:block">
                <DiamondGlyph size={240} stroke="var(--brand-gold)" />
            </div>

            <div className="relative mx-auto max-w-[1500px] px-5 pb-20 pt-10 lg:px-10 lg:pb-24 lg:pt-14">
                {/* Breadcrumb */}
                <nav className="eyebrow mb-8 flex items-center gap-2" style={{ color: 'var(--brand-muted)' }}>
                    <Link href="/" className="transition hover:text-yellow-600" style={{ color: 'var(--brand-muted)' }}>Home</Link>
                    <span className="opacity-50">/</span>
                    <span style={{ color: 'var(--brand-ink)' }}>Journal</span>
                </nav>

                <div className="grid items-end gap-10 lg:grid-cols-12">
                    <div className="lg:col-span-8">
                        <div className="eyebrow mb-6 flex items-center gap-3" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>
                            <DiamondGlyph size={12} stroke="var(--brand-gold)" />
                            The Husnulwari Journal · Vol. 12
                        </div>

                        <h1
                            className="font-display leading-[0.96] tracking-[-0.015em]"
                            style={{ fontSize: 'clamp(48px,7.5vw,108px)' }}
                        >
                            Style, fabric &amp;<br />
                            <span className="italic" style={{ color: 'var(--brand-gold)' }}>modest fashion journal.</span>
                        </h1>

                        <p className="mt-7 max-w-[600px] leading-[1.75]" style={{ fontSize: '16.5px', color: 'var(--brand-muted)' }}>
                            Helpful guides, styling ideas, and fabric knowledge to help you choose the perfect material for Punjabi, shirt, Kabli, and ready-made modest wear — before you buy.
                        </p>

                        {/* Search */}
                        <form
                            onSubmit={(e) => { e.preventDefault(); onSearch(); }}
                            className="mt-8 flex max-w-[540px] items-center border py-2 pl-5 pr-2 transition focus-within:border-yellow-600"
                            style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-cream)' }}
                        >
                            <svg width="18" height="18" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" className="mr-3 shrink-0" style={{ color: 'var(--brand-gold)' }}>
                                <circle cx="9" cy="9" r="7" /><path d="M19 19l-5-5" strokeLinecap="round" />
                            </svg>
                            <input
                                value={query}
                                onChange={(e) => setQuery(e.target.value)}
                                placeholder="Search fabric guides, styling tips, Kabli, Eid…"
                                className="flex-1 bg-transparent py-2.5 text-[14px] outline-none"
                                style={{ color: 'var(--brand-ink)' }}
                            />
                            <button
                                type="submit"
                                className="px-5 py-3 text-[11px] uppercase tracking-[0.18em] transition hover:bg-yellow-600"
                                style={{ backgroundColor: 'var(--brand-slate)', color: 'var(--brand-ivory)' }}
                            >
                                Explore Guides
                            </button>
                        </form>

                        <div className="mt-5 flex flex-wrap items-center gap-3 text-[12px]" style={{ color: 'var(--brand-muted)' }}>
                            <span className="eyebrow" style={{ color: 'var(--brand-muted)' }}>Trending:</span>
                            {['Punjabi Fabric', 'Eid Styling', 'Fabric Care', 'Kabli Guide'].map((t) => (
                                <button
                                    key={t}
                                    onClick={() => { setQuery(t); router.get('/blog', { search: t }); }}
                                    className="link-gold pb-0.5 transition hover:text-yellow-600"
                                    style={{ color: 'var(--brand-muted)' }}
                                >
                                    {t}
                                </button>
                            ))}
                        </div>
                    </div>

                    <div className="lg:col-span-4">
                        <div className="relative">
                            <Placeholder label="journal · folded fabric" ratio="3/4" />
                            <div
                                className="-bottom-5 -left-5 hidden max-w-[200px] border p-4 md:absolute md:block"
                                style={{ backgroundColor: 'var(--brand-cream)', borderColor: 'var(--brand-line)' }}
                            >
                                <div className="eyebrow mb-1.5" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>This Week</div>
                                <div className="font-display text-[18px] leading-tight" style={{ color: 'var(--brand-ink)' }}>
                                    5 fabric weights for Bangladeshi summer
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
}

// ─── Featured Article ─────────────────────────────────────────────────────────

function FeaturedArticle({ post }: { post: BlogPost }) {
    return (
        <section style={{ backgroundColor: 'var(--brand-cream)' }}>
            <div className="mx-auto max-w-[1500px] px-5 py-20 lg:px-10 lg:py-24">
                <div className="mb-10 flex flex-wrap items-end justify-between gap-4">
                    <SectionEyebrow>Featured Guide</SectionEyebrow>
                    <Link
                        href="#all"
                        className="eyebrow flex items-center gap-2 transition hover:text-yellow-600"
                        style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}
                    >
                        All articles <ArrowIcon />
                    </Link>
                </div>

                <Link href={`/blog/${post.slug}`} className="group card-lift grid items-center gap-8 lg:grid-cols-12 lg:gap-12">
                    <div className="relative lg:col-span-7">
                        <PostImage post={post} ratio="16/10" dark />
                        <div className="absolute left-5 top-5 flex items-center gap-2">
                            {post.category && (
                                <span className="eyebrow px-3 py-1.5" style={{ backgroundColor: 'var(--brand-gold)', color: 'var(--brand-slate)' }}>
                                    {post.category.name}
                                </span>
                            )}
                            <span className="eyebrow px-3 py-1.5 backdrop-blur" style={{ backgroundColor: 'rgba(246,241,231,0.85)' }}>
                                Featured
                            </span>
                        </div>
                        <div
                            className="absolute bottom-5 right-5 flex h-12 w-12 items-center justify-center rounded-full backdrop-blur transition group-hover:bg-yellow-500 group-hover:text-white"
                            style={{ backgroundColor: 'rgba(246,241,231,0.85)' }}
                        >
                            <svg width="16" height="16" viewBox="0 0 14 14" fill="none">
                                <path d="M3 11L11 3M5 3h6v6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                        </div>
                    </div>

                    <div className="lg:col-span-5">
                        <div className="eyebrow mb-4 flex items-center gap-3" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>
                            {formatDate(post.created_at)}
                            <span className="opacity-50">·</span>
                            {readTime(post)} min read
                        </div>
                        <h2
                            className="font-display leading-[1.02] tracking-[-0.01em] transition-colors group-hover:text-yellow-700"
                            style={{ fontSize: 'clamp(34px,4.5vw,60px)', color: 'var(--brand-ink)' }}
                        >
                            {post.title}
                        </h2>
                        {post.excerpt && (
                            <p className="mt-6 max-w-[520px] leading-[1.85] text-[16px]" style={{ color: 'var(--brand-muted)' }}>
                                {post.excerpt}
                            </p>
                        )}

                        <div className="mt-8 flex items-center justify-between border-t pt-6" style={{ borderColor: 'var(--brand-line)' }}>
                            <div className="flex items-center gap-3">
                                <div
                                    className="flex h-10 w-10 items-center justify-center rounded-full border"
                                    style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-ivory)' }}
                                >
                                    <DiamondGlyph size={14} stroke="var(--brand-gold)" />
                                </div>
                                <div>
                                    <div className="text-[13px] font-medium" style={{ color: 'var(--brand-ink)' }}>Editorial Team</div>
                                    <div className="eyebrow" style={{ fontSize: '9px', color: 'var(--brand-muted)' }}>Husnulwari Atelier</div>
                                </div>
                            </div>
                            <span className="inline-flex items-center gap-3 text-[12px] uppercase tracking-[0.18em] transition-colors group-hover:text-yellow-700" style={{ color: 'var(--brand-ink)' }}>
                                Read article <ArrowIcon />
                            </span>
                        </div>
                    </div>
                </Link>
            </div>
        </section>
    );
}

// ─── Category Rail ────────────────────────────────────────────────────────────

function CategoryRail({
    value,
    onChange,
    categories,
}: {
    value: string;
    onChange: (slug: string) => void;
    categories: BlogCategory[];
}) {
    const allCats = [{ id: 0, name: 'All', slug: '' }, ...categories];

    return (
        <section
            className="sticky z-30 border-y"
            style={{ top: '74px', backgroundColor: 'var(--brand-cream)', borderColor: 'var(--brand-line)' }}
        >
            <div className="mx-auto max-w-[1500px] px-5 lg:px-10">
                <div className="no-scrollbar -mx-1 flex items-center gap-3 overflow-x-auto py-4">
                    {allCats.map((c) => {
                        const active = value === c.slug;
                        return (
                            <button
                                key={c.id}
                                onClick={() => onChange(c.slug)}
                                className="inline-flex shrink-0 items-center gap-2 whitespace-nowrap border px-4 py-2 text-[12px] uppercase tracking-[0.16em] transition"
                                style={{
                                    backgroundColor: active ? 'var(--brand-slate)' : 'var(--brand-ivory)',
                                    borderColor: active ? 'var(--brand-slate)' : 'var(--brand-line)',
                                    color: active ? 'var(--brand-ivory)' : 'rgba(26,31,35,0.8)',
                                }}
                            >
                                {active && <DiamondGlyph size={9} stroke="var(--brand-gold)" />}
                                {c.name}
                            </button>
                        );
                    })}
                </div>
            </div>
        </section>
    );
}

// ─── Blog Card ────────────────────────────────────────────────────────────────

function BlogCard({ post }: { post: BlogPost }) {
    return (
        <Link href={`/blog/${post.slug}`} className="group card-lift block">
            <div className="relative overflow-hidden">
                <PostImage post={post} ratio="4/5" />
                {post.category && (
                    <div className="absolute left-4 top-4">
                        <span className="eyebrow px-3 py-1.5 backdrop-blur" style={{ backgroundColor: 'rgba(246,241,231,0.88)' }}>
                            {post.category.name}
                        </span>
                    </div>
                )}
            </div>
            <div className="pt-5">
                <div className="eyebrow mb-3 flex items-center gap-2" style={{ color: 'var(--brand-muted)' }}>
                    {formatDate(post.created_at)}
                    <span className="opacity-50">·</span>
                    {readTime(post)} min read
                </div>
                <h3
                    className="font-display text-[24px] leading-[1.15] transition-colors group-hover:text-yellow-700 lg:text-[26px]"
                    style={{ color: 'var(--brand-ink)' }}
                >
                    {post.title}
                </h3>
                {post.excerpt && (
                    <p className="mt-3 line-clamp-3 text-[14px] leading-[1.75]" style={{ color: 'var(--brand-muted)' }}>
                        {post.excerpt}
                    </p>
                )}
                <div
                    className="mt-4 inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.18em] transition-colors group-hover:text-yellow-700"
                    style={{ color: 'rgba(26,31,35,0.8)' }}
                >
                    Read more <ArrowIcon size={13} />
                </div>
            </div>
        </Link>
    );
}

// ─── Blog Sidebar ─────────────────────────────────────────────────────────────

function BlogSidebar({ categories, recentPosts, phone }: { categories: BlogCategory[]; recentPosts: BlogPost[]; phone: string }) {
    const [email, setEmail] = useState('');
    const [done, setDone] = useState(false);
    const [sideSearch, setSideSearch] = useState('');

    const waUrl = `https://wa.me/${phone.replace(/\D/g, '')}`;

    return (
        <aside className="space-y-10 lg:space-y-12">
            {/* Search */}
            <div className="border p-6" style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}>
                <div className="mb-4 flex items-center gap-3">
                    <DiamondGlyph size={14} stroke="var(--brand-gold)" />
                    <h3 className="font-display text-[22px] leading-none" style={{ color: 'var(--brand-ink)' }}>Search</h3>
                </div>
                <form
                    onSubmit={(e) => { e.preventDefault(); if (sideSearch.trim()) router.get('/blog', { search: sideSearch.trim() }); }}
                    className="flex items-center border transition focus-within:border-yellow-500"
                    style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-cream)' }}
                >
                    <svg width="16" height="16" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" className="ml-4 mr-3 shrink-0" style={{ color: 'var(--brand-gold)' }}>
                        <circle cx="9" cy="9" r="7" /><path d="M19 19l-5-5" strokeLinecap="round" />
                    </svg>
                    <input
                        value={sideSearch}
                        onChange={(e) => setSideSearch(e.target.value)}
                        placeholder="Search fabric guides…"
                        className="flex-1 bg-transparent py-3 text-[13px] outline-none"
                        style={{ color: 'var(--brand-ink)' }}
                    />
                </form>
            </div>

            {/* Popular Categories */}
            {categories.length > 0 && (
                <div>
                    <div className="eyebrow mb-5" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>Popular Categories</div>
                    <ul className="space-y-3">
                        {categories.slice(0, 6).map((c) => (
                            <li key={c.id}>
                                <Link
                                    href={`/blog?category=${c.slug}`}
                                    className="group flex items-center justify-between border-b py-2 transition hover:text-yellow-700"
                                    style={{ borderColor: 'rgba(229,221,204,0.6)', color: 'var(--brand-ink)' }}
                                >
                                    <span className="flex items-center gap-3 text-[14px]">
                                        <DiamondGlyph size={9} stroke="var(--brand-gold)" />
                                        {c.name}
                                    </span>
                                </Link>
                            </li>
                        ))}
                    </ul>
                </div>
            )}

            {/* Popular Posts */}
            {recentPosts.length > 0 && (
                <div>
                    <div className="eyebrow mb-5" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>Popular Posts</div>
                    <ul className="space-y-5">
                        {recentPosts.slice(0, 4).map((p) => (
                            <li key={p.id}>
                                <Link href={`/blog/${p.slug}`} className="group flex gap-4">
                                    <div className="w-[88px] shrink-0">
                                        <PostImage post={p} ratio="4/5" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        {p.category && (
                                            <div className="eyebrow mb-1" style={{ fontSize: '9px', color: 'var(--brand-gold-dim, var(--brand-gold))' }}>
                                                {p.category.name}
                                            </div>
                                        )}
                                        <div className="line-clamp-2 font-display text-[17px] leading-tight transition-colors group-hover:text-yellow-700" style={{ color: 'var(--brand-ink)' }}>
                                            {p.title}
                                        </div>
                                        <div className="mt-2 text-[11px]" style={{ color: 'var(--brand-muted)' }}>{formatDate(p.created_at)}</div>
                                    </div>
                                </Link>
                            </li>
                        ))}
                    </ul>
                </div>
            )}

            {/* Newsletter */}
            <div className="relative overflow-hidden p-7 text-white" style={{ backgroundColor: 'var(--brand-slate)' }}>
                <div className="pointer-events-none absolute -right-6 -top-6 opacity-15">
                    <DiamondGlyph size={140} stroke="var(--brand-gold)" />
                </div>
                <div className="relative">
                    <DiamondGlyph size={14} stroke="var(--brand-gold)" />
                    <h3 className="font-display mt-3 text-[26px] leading-tight">Get fabric &amp; style tips</h3>
                    <p className="mt-2 text-[13px] leading-relaxed" style={{ color: 'rgba(251,247,239,0.7)' }}>
                        Join our list for new fabric arrivals, styling ideas, and ready-made Punjabi updates.
                    </p>
                    <form
                        onSubmit={(e) => { e.preventDefault(); if (email) setDone(true); }}
                        className="mt-5 space-y-2"
                    >
                        <input
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            placeholder="your@email.com"
                            required
                            className="w-full border bg-transparent px-4 py-3 text-[13px] outline-none transition"
                            style={{ borderColor: 'rgba(251,247,239,0.25)', color: 'white' }}
                        />
                        <button
                            className="w-full py-3 text-[11px] uppercase tracking-[0.18em] font-medium transition"
                            style={{ backgroundColor: 'var(--brand-gold)', color: 'var(--brand-slate)' }}
                        >
                            {done ? 'Welcome ✦' : 'Subscribe'}
                        </button>
                    </form>
                    <p className="mt-3 tracking-wider text-[10px]" style={{ color: 'rgba(251,247,239,0.4)' }}>No spam. Unsubscribe anytime.</p>
                </div>
            </div>

            {/* WhatsApp help card */}
            <div className="border p-6" style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}>
                <div className="eyebrow mb-3" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>Atelier Help</div>
                <h3 className="font-display text-[22px] leading-tight" style={{ color: 'var(--brand-ink)' }}>Need a fabric suggestion?</h3>
                <p className="mt-2 text-[13px] leading-relaxed" style={{ color: 'var(--brand-muted)' }}>
                    WhatsApp our atelier team — share what you're making and we'll suggest the right weight, colour, and yardage.
                </p>
                {phone && (
                    <a
                        href={waUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="mt-4 inline-flex items-center gap-2 eyebrow transition hover:text-yellow-600"
                        style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}
                    >
                        Message us <ArrowIcon size={12} />
                    </a>
                )}
            </div>
        </aside>
    );
}

// ─── Blog Grid + Sidebar ──────────────────────────────────────────────────────

function BlogGridWithSidebar({
    posts,
    categories,
    activeCat,
    phone,
}: {
    posts: PaginatedData<BlogPost>;
    categories: BlogCategory[];
    activeCat: string;
    phone: string;
}) {
    const gridPosts = posts.data;

    return (
        <section id="all" style={{ backgroundColor: 'var(--brand-cream)' }}>
            <div className="mx-auto max-w-[1500px] px-5 py-20 lg:px-10 lg:py-24">
                <div className="mb-12 flex flex-wrap items-end justify-between gap-4">
                    <div>
                        <SectionEyebrow>All Articles</SectionEyebrow>
                        <h2
                            className="font-display leading-tight"
                            style={{ fontSize: 'clamp(34px,4vw,52px)', color: 'var(--brand-ink)' }}
                        >
                            {activeCat
                                ? <>From the <span className="italic" style={{ color: 'var(--brand-gold)' }}>{categories.find((c) => c.slug === activeCat)?.name ?? activeCat}</span> series</>
                                : 'Recent journal entries'}
                        </h2>
                    </div>
                    <div className="eyebrow" style={{ color: 'var(--brand-muted)' }}>
                        {posts.total} {posts.total === 1 ? 'article' : 'articles'}
                    </div>
                </div>

                <div className="grid gap-10 lg:grid-cols-[1fr_320px] lg:gap-14">
                    <div>
                        {gridPosts.length === 0 ? (
                            <div className="border bg-ivory py-24 text-center" style={{ borderColor: 'var(--brand-line)', backgroundColor: 'var(--brand-ivory)' }}>
                                <div
                                    className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-full border"
                                    style={{ borderColor: 'var(--brand-line)' }}
                                >
                                    <DiamondGlyph size={22} stroke="var(--brand-gold)" />
                                </div>
                                <h3 className="font-display text-[28px]" style={{ color: 'var(--brand-ink)' }}>No articles match yet.</h3>
                                <p className="mt-2 text-[14px]" style={{ color: 'var(--brand-muted)' }}>Try another category or clear your search.</p>
                                <Link
                                    href="/blog"
                                    className="mt-5 inline-flex items-center gap-2 eyebrow transition hover:text-yellow-600"
                                    style={{ color: 'var(--brand-gold)' }}
                                >
                                    Clear filters <ArrowIcon size={12} />
                                </Link>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 gap-x-6 gap-y-14 sm:grid-cols-2">
                                {gridPosts.map((p) => <BlogCard key={p.id} post={p} />)}
                            </div>
                        )}

                        {posts.last_page > 1 && (
                            <div
                                className="mt-16 flex flex-wrap items-center justify-between gap-4 border-t pt-8"
                                style={{ borderColor: 'var(--brand-line)' }}
                            >
                                <div className="eyebrow" style={{ color: 'var(--brand-muted)' }}>
                                    Page {posts.current_page} of {posts.last_page} · {posts.total} articles
                                </div>
                                <div className="flex items-center gap-1">
                                    {posts.links.map((link, i) => (
                                        <button
                                            key={i}
                                            disabled={!link.url}
                                            onClick={() => link.url && router.visit(link.url)}
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                            className="h-10 min-w-[40px] 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 ? 'var(--brand-ivory)' : 'rgba(26,31,35,0.7)',
                                            }}
                                        />
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>

                    <BlogSidebar categories={categories} recentPosts={posts.data} phone={phone} />
                </div>
            </div>
        </section>
    );
}

// ─── Educational Highlight ────────────────────────────────────────────────────

function EducationalHighlight() {
    const cards = [
        { n: '01', t: 'See the final look', s: 'Understand how a fabric may appear after stitching — through real photos of the same bolt as Punjabi, shirt, and Kabli.' },
        { n: '02', t: 'Choose with confidence', s: "Learn about fabric weight, colour, fall, and breathability — so you order yardage you'll actually wear." },
        { n: '03', t: 'Plan your outfit better', s: 'Get specific ideas for Jummah, Eid, family gatherings, and everyday wear — paired with our current bolts.' },
    ];

    const icons = [
        // Eye
        <svg key="eye" width="20" height="20" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="3" /><path d="M2 11s3-6 9-6 9 6 9 6-3 6-9 6-9-6-9-6z" /></svg>,
        // Scale/balance
        <svg key="scale" width="20" height="20" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 3v16M3 8h16M5 11l2-3 2 3a2 2 0 11-4 0zM13 11l2-3 2 3a2 2 0 11-4 0z" /></svg>,
        // Calendar
        <svg key="cal" width="20" height="20" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="16" height="14" /><path d="M3 9h16M8 3v4M14 3v4" /></svg>,
    ];

    return (
        <section className="border-y" style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}>
            <div className="mx-auto max-w-[1500px] px-5 py-24 lg:px-10 lg:py-28">
                <div className="mb-14 grid items-end gap-10 lg:grid-cols-12">
                    <div className="lg:col-span-7">
                        <SectionEyebrow>For the curious buyer</SectionEyebrow>
                        <h2
                            className="font-display leading-[1] tracking-[-0.01em]"
                            style={{ fontSize: 'clamp(38px,5vw,68px)', color: 'var(--brand-ink)' }}
                        >
                            Not sure which fabric<br />
                            <span className="italic" style={{ color: 'var(--brand-gold)' }}>to choose?</span>
                        </h2>
                    </div>
                    <div className="lg:col-span-5">
                        <p className="max-w-[460px] leading-[1.85] text-[16px]" style={{ color: 'var(--brand-muted)' }}>
                            Choosing fabric can be difficult when you can't picture the final outfit. Our guides help you understand how each fabric may look as a Punjabi, shirt, or Kabli — <span style={{ color: 'var(--brand-ink)' }}>before you buy.</span>
                        </p>
                    </div>
                </div>

                <div className="grid gap-5 md:grid-cols-3 lg:gap-6">
                    {cards.map((c, i) => (
                        <div
                            key={c.n}
                            className="card-lift group relative border p-8 transition hover:border-yellow-500 lg:p-10"
                            style={{ backgroundColor: 'var(--brand-cream)', borderColor: 'var(--brand-line)' }}
                        >
                            <div className="mb-7 flex items-center justify-between">
                                <span className="font-display text-[44px] italic leading-none" style={{ color: 'var(--brand-gold)' }}>{c.n}</span>
                                <div
                                    className="flex h-10 w-10 items-center justify-center rounded-full border transition group-hover:border-yellow-500"
                                    style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-gold)' }}
                                >
                                    {icons[i]}
                                </div>
                            </div>
                            <h3 className="font-display mb-3 text-[26px] leading-tight" style={{ color: 'var(--brand-ink)' }}>{c.t}</h3>
                            <p className="text-[14px] leading-[1.8]" style={{ color: 'var(--brand-muted)' }}>{c.s}</p>
                            <div className="hairline mt-7" />
                            <div className="mt-5 eyebrow flex items-center gap-2" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>
                                <DiamondGlyph size={9} stroke="var(--brand-gold)" /> Guide series
                            </div>
                        </div>
                    ))}
                </div>

                <div className="mt-14 text-center">
                    <a
                        href="#all"
                        className="inline-flex items-center gap-3 px-8 py-4 text-[12px] uppercase tracking-[0.18em] font-medium transition"
                        style={{ backgroundColor: 'var(--brand-slate)', color: 'var(--brand-ivory)' }}
                        onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--brand-gold)'; e.currentTarget.style.color = 'var(--brand-slate)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'var(--brand-slate)'; e.currentTarget.style.color = 'var(--brand-ivory)'; }}
                    >
                        Explore Fabric Guides <ArrowIcon />
                    </a>
                </div>
            </div>
        </section>
    );
}

// ─── Style Inspiration ────────────────────────────────────────────────────────

function StyleInspiration() {
    const items = [
        { t: 'Punjabi Look Ideas', c: 'Sage and ivory pairings for Jummah, work, and gatherings.', tag: 'Editorial', dark: false },
        { t: 'Kabli Styling', c: 'Textured weaves and considered colours for a smart traditional look.', tag: 'Mens', dark: true },
        { t: 'Shirt Fabric Looks', c: 'Three plain bolts, three finished looks — from desk to dinner.', tag: 'Daily', dark: false },
        { t: 'Eid Outfit Planning', c: 'How to coordinate Punjabi, Kabli, and abaya across the family.', tag: 'Eid', dark: true },
    ];

    return (
        <section style={{ backgroundColor: 'var(--brand-cream)' }}>
            <div className="mx-auto max-w-[1500px] px-5 py-24 lg:px-10 lg:py-28">
                <div className="mb-12 flex flex-wrap items-end justify-between gap-6">
                    <div>
                        <SectionEyebrow>Style Inspiration</SectionEyebrow>
                        <h2
                            className="font-display leading-[1]"
                            style={{ fontSize: 'clamp(38px,5vw,68px)', color: 'var(--brand-ink)' }}
                        >
                            How the bolt<br />
                            <span className="italic" style={{ color: 'var(--brand-gold)' }}>becomes the outfit.</span>
                        </h2>
                    </div>
                    <Link
                        href="/blog"
                        className="eyebrow flex items-center gap-2 transition hover:text-yellow-600"
                        style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}
                    >
                        All inspiration <ArrowIcon />
                    </Link>
                </div>

                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 lg:gap-6">
                    {items.map((it) => (
                        <Link href="/products" key={it.t} className="group card-lift block">
                            <div className="relative overflow-hidden">
                                <Placeholder label={`inspiration · ${it.t.toLowerCase()}`} dark={it.dark} ratio="4/5" />
                                <div className="absolute left-4 top-4">
                                    <span className="eyebrow px-3 py-1.5 backdrop-blur" style={{ backgroundColor: 'rgba(246,241,231,0.88)' }}>
                                        {it.tag}
                                    </span>
                                </div>
                                <div
                                    className="absolute bottom-4 right-4 flex h-9 w-9 items-center justify-center rounded-full backdrop-blur transition group-hover:bg-yellow-500 group-hover:text-white"
                                    style={{ backgroundColor: 'rgba(246,241,231,0.88)' }}
                                >
                                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                                        <path d="M3 11L11 3M5 3h6v6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                </div>
                            </div>
                            <div className="pt-5">
                                <div className="font-display text-[24px] leading-tight transition-colors group-hover:text-yellow-700" style={{ color: 'var(--brand-ink)' }}>
                                    {it.t}
                                </div>
                                <p className="mt-2 text-[13px] leading-relaxed" style={{ color: 'var(--brand-muted)' }}>{it.c}</p>
                                <div className="mt-4 inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] transition-colors group-hover:text-yellow-700" style={{ color: 'rgba(26,31,35,0.8)' }}>
                                    View Guide <ArrowIcon size={11} />
                                </div>
                            </div>
                        </Link>
                    ))}
                </div>
            </div>
        </section>
    );
}

// ─── Blog FAQ ─────────────────────────────────────────────────────────────────

function BlogFAQ() {
    const faqs = [
        { q: 'What kind of blog articles will I find here?', a: 'Practical, friendly guides about fabric weights, colour choice, how a bolt looks after stitching, modest styling, fabric care, and ready-made Punjabi updates. We write for people choosing fabric for the first time and for tailors and stylists alike.' },
        { q: 'Can your guides help me choose fabric?', a: 'Yes — that\'s the whole point. Each fabric guide includes weight, breathability, drape, recommended uses (Punjabi / shirt / Kabli), and seasonal notes. If you\'re stuck, send us a photo and we\'ll suggest a pairing on WhatsApp.' },
        { q: 'Do you explain how fabric may look after stitching?', a: 'Where possible, we publish side-by-side photos of the same bolt as a Punjabi, shirt, or Kabli set. Texture, fall, and behaviour after pressing all change once it\'s stitched — our articles show that transition.' },
        { q: 'Will you share ready-made Punjabi updates?', a: 'Yes. As we expand into ready-made pieces, every drop is announced first in the journal — with fabric origin, sizing notes, and styling. Subscribe to the newsletter to get it before the shop.' },
        { q: 'Can I contact you for fabric suggestions?', a: 'Absolutely. Drop us a message on WhatsApp with what you\'re making and your budget per yard. Our atelier team replies personally within a few hours, six days a week.' },
    ];
    const [open, setOpen] = useState(0);

    return (
        <section className="border-y" style={{ backgroundColor: 'var(--brand-ivory)', borderColor: 'var(--brand-line)' }}>
            <div className="mx-auto max-w-[1500px] grid gap-12 px-5 py-24 lg:grid-cols-12 lg:px-10 lg:py-28">
                <div className="lg:col-span-4">
                    <SectionEyebrow>Journal FAQs</SectionEyebrow>
                    <h2
                        className="font-display leading-[1.02]"
                        style={{ fontSize: 'clamp(36px,5vw,60px)', color: 'var(--brand-ink)' }}
                    >
                        What to expect<br /><span className="italic" style={{ color: 'var(--brand-gold)' }}>from the journal.</span>
                    </h2>
                    <p className="mt-6 max-w-[320px] leading-relaxed text-[15px]" style={{ color: 'var(--brand-muted)' }}>
                        A few honest answers about what we publish, who it's for, and how to use it before you buy.
                    </p>
                </div>
                <div className="lg:col-span-8">
                    {faqs.map((f, i) => {
                        const isOpen = open === i;
                        return (
                            <div key={i} className="border-b" style={{ borderColor: 'var(--brand-line)' }}>
                                <button
                                    className="group flex w-full items-center justify-between gap-6 py-6 text-left"
                                    onClick={() => setOpen(isOpen ? -1 : i)}
                                >
                                    <span className="font-display pr-4 text-[22px] leading-tight lg:text-[26px]" style={{ color: 'var(--brand-ink)' }}>
                                        <span className="mr-4 align-middle font-mono text-[11px]" style={{ color: 'var(--brand-gold-dim, var(--brand-gold))' }}>0{i + 1}</span>
                                        {f.q}
                                    </span>
                                    <span
                                        className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition"
                                        style={{
                                            borderColor: isOpen ? 'var(--brand-gold)' : 'var(--brand-line)',
                                            backgroundColor: isOpen ? 'var(--brand-gold)' : 'transparent',
                                            color: isOpen ? 'var(--brand-ivory)' : 'rgba(26,31,35,0.6)',
                                        }}
                                    >
                                        <svg width="12" height="12" viewBox="0 0 12 12">
                                            <path
                                                d="M6 2v8M2 6h8"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                style={{ transform: isOpen ? 'rotate(45deg)' : 'none', transformOrigin: 'center', transition: 'transform .3s' }}
                                            />
                                        </svg>
                                    </span>
                                </button>
                                <div
                                    className="overflow-hidden transition-all duration-500"
                                    style={{ maxHeight: isOpen ? 300 : 0, opacity: isOpen ? 1 : 0 }}
                                >
                                    <p className="pb-6 pr-12 text-[15px] leading-[1.85]" style={{ color: 'var(--brand-muted)' }}>{f.a}</p>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
        </section>
    );
}

// ─── Blog CTA ─────────────────────────────────────────────────────────────────

function BlogCTA() {
    return (
        <section className="relative overflow-hidden text-white" style={{ backgroundColor: 'var(--brand-ink)' }}>
            <div className="absolute inset-0 ph-stripe-dark opacity-25" />
            <div className="pointer-events-none absolute left-1/2 top-10 -translate-x-1/2 opacity-10">
                <DiamondGlyph size={420} stroke="var(--brand-gold)" />
            </div>
            <div className="relative mx-auto max-w-[1100px] px-5 py-24 text-center lg:px-10 lg:py-28">
                <SectionEyebrow tone="ivory">Read · Then choose</SectionEyebrow>
                <h2
                    className="font-display leading-[1] tracking-[-0.01em]"
                    style={{ fontSize: 'clamp(44px,6vw,84px)' }}
                >
                    Ready to choose<br />
                    <span className="italic" style={{ color: 'var(--brand-gold)' }}>your next fabric?</span>
                </h2>
                <p className="mx-auto mt-7 max-w-[560px] text-[16px] leading-[1.85]" style={{ color: 'rgba(251,247,239,0.7)' }}>
                    Explore our latest fabric collection and use our guides to choose the perfect material for Punjabi, shirt, or Kabli.
                </p>
                <div className="mt-10 flex flex-col justify-center gap-3 sm:flex-row">
                    <Link
                        href="/products"
                        className="inline-flex items-center justify-center px-8 py-4 text-[12px] uppercase tracking-[0.18em] font-medium transition"
                        style={{ backgroundColor: 'var(--brand-gold)', color: 'var(--brand-slate)' }}
                        onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--brand-ivory)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'var(--brand-gold)'; }}
                    >
                        Shop Fabrics
                    </Link>
                    <Link
                        href="/products"
                        className="inline-flex items-center justify-center border px-8 py-4 text-[12px] uppercase tracking-[0.18em] transition"
                        style={{ borderColor: 'rgba(251,247,239,0.3)', color: 'white' }}
                        onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--brand-gold)'; e.currentTarget.style.color = 'var(--brand-gold)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'rgba(251,247,239,0.3)'; e.currentTarget.style.color = 'white'; }}
                    >
                        View Ready-Made Punjabi →
                    </Link>
                </div>
                <div className="mt-10 eyebrow flex items-center justify-center gap-3" style={{ color: 'rgba(251,247,239,0.4)' }}>
                    <DiamondGlyph size={10} stroke="var(--brand-gold)" />
                    New fabric arrivals · Every Thursday
                </div>
            </div>
        </section>
    );
}

// ─── Page Footer ──────────────────────────────────────────────────────────────

function PageFooter() {
    const { siteSettings } = usePage<SharedData>().props;
    const s = siteSettings;
    const siteName = s?.site_name ?? 'Husnulwari';
    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 fabric, 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>
    );
}

// ─── Inner (wrapped in LangProvider) ─────────────────────────────────────────

function BlogInner({ posts, categories, filters }: Props) {
    const { siteSettings } = usePage<SharedData>().props;
    const siteName = siteSettings?.site_name ?? 'Husnulwari';
    const showAnnouncement = siteSettings?.show_announcement ?? true;
    const announcementText = siteSettings?.announcement_bar ?? '';
    const phone = siteSettings?.phone ?? '';

    const [activeCat, setActiveCat] = useState(filters.category ?? '');
    const [heroQuery, setHeroQuery] = useState(filters.search ?? '');

    const handleCatChange = (slug: string) => {
        setActiveCat(slug);
        const params: Record<string, string> = {};
        if (slug) params.category = slug;
        if (filters.search) params.search = filters.search;
        router.get('/blog', params, { preserveScroll: false });
    };

    const handleHeroSearch = () => {
        const params: Record<string, string> = {};
        if (heroQuery.trim()) params.search = heroQuery.trim();
        if (activeCat) params.category = activeCat;
        router.get('/blog', params);
    };

    const featuredPost = posts.data[0] ?? null;
    const siteMeta = `${siteName} Journal`;

    return (
        <div style={{ fontFamily: "'Outfit', 'Instrument Sans', sans-serif", backgroundColor: 'var(--brand-cream)' }}>
            <Head title={`Blog — ${siteMeta}`} />

            {/* Announcement marquee */}
            {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="blog" searchPath="/blog" />
            <BlogHero query={heroQuery} setQuery={setHeroQuery} onSearch={handleHeroSearch} />

            {featuredPost && <FeaturedArticle post={featuredPost} />}

            <CategoryRail value={activeCat} onChange={handleCatChange} categories={categories} />

            <BlogGridWithSidebar
                posts={posts}
                categories={categories}
                activeCat={activeCat}
                phone={phone}
            />

            <EducationalHighlight />
            <StyleInspiration />
            <BlogFAQ />
            <BlogCTA />
            <PageFooter />
        </div>
    );
}

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

export default function BlogIndex(props: Props) {
    return (
        <LangProvider>
            <BlogInner {...props} />
        </LangProvider>
    );
}
