import { Head, Link, router } from '@inertiajs/react';
import { Check, ChevronDown, Minus, PackageCheck, Plus, Ruler, ShieldCheck, ShoppingBag, Tag, Trash2, Truck, X } from 'lucide-react';
import { useMemo, useState } from 'react';

import FrontendLayout from '@/layouts/frontend-layout';
import { useLang } from '@/lib/lang';
import { xsrfToken } from '@/lib/utils';

interface CartItem {
    row_id: string;
    product_id: number;
    variant_id: number | null;
    name: string;
    variant_label: string | null;
    price: number;
    qty: number;
    image: string | null;
    product_type: string;
}

interface CartTotals {
    subtotal: number;
    discount: number;
    shipping: number;
    total: number;
    coupon_code: string | null;
}

type Usage = 'Punjabi' | 'Shirt' | 'Kabli' | 'Ready-Made';

const COLOR_HEX: Record<string, string> = {
    black: '#1A1F23',
    blue: '#2A3E55',
    brown: '#7A5A3A',
    cream: '#EAE0CB',
    gray: '#6F6F6F',
    green: '#8C8042',
    grey: '#6F6F6F',
    maroon: '#6B2E2E',
    navy: '#2A3E55',
    olive: '#8C8042',
    red: '#8E3B2E',
    sage: '#A8AA8E',
    white: '#F4EEDF',
};

const usageGuides: Array<{ type: Usage; length: string; href: string }> = [
    { type: 'Shirt', length: '2.5-3 yd', href: '/products?search=shirt' },
    { type: 'Punjabi', length: '3.5-4 yd', href: '/products?search=punjabi' },
    { type: 'Kabli', length: '4-5+ yd', href: '/products?search=kabli' },
];

const recommended = [
    { name: 'Cream Premium Punjabi Fabric', color: '#EAE0CB', price: 3250 },
    { name: 'Deep Navy Kabli Fabric', color: '#2A3E55', price: 3400 },
    { name: 'Black Soft Shirt Fabric', color: '#1A1F23', price: 2800 },
    { name: 'Maroon Traditional Fabric', color: '#6B2E2E', price: 2750 },
];

function formatMoney(value: number) {
    return `Tk ${Number(value || 0).toLocaleString()}`;
}

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

function inferUsage(item: CartItem): Usage {
    const text = `${item.name} ${item.variant_label ?? ''}`.toLowerCase();
    if (text.includes('ready')) return 'Ready-Made';
    if (text.includes('shirt')) return 'Shirt';
    if (text.includes('kabli')) return 'Kabli';
    return 'Punjabi';
}

function inferLength(usage: Usage) {
    if (usage === 'Shirt') return '3 yd';
    if (usage === 'Kabli') return '4.5 yd';
    if (usage === 'Ready-Made') return 'Size selected';
    return '4 yd';
}

function inferColor(item: CartItem) {
    const text = `${item.variant_label ?? ''} ${item.name}`.toLowerCase();
    const match = Object.entries(COLOR_HEX).find(([name]) => text.includes(name));
    return match ? { name: match[0], hex: match[1] } : { name: 'olive', hex: '#8C8042' };
}

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

function FragranceBottleFallback() {
    return (
        <div
            className="flex h-full w-full items-center justify-center"
            style={{ background: 'linear-gradient(145deg, #F9F4EC 0%, #EDE5D8 100%)' }}
        >
            <svg viewBox="0 0 60 100" fill="none" style={{ width: '38px', opacity: 0.45 }}>
                <rect x="25" y="1" width="10" height="13" rx="3" fill="#B8893F" />
                <rect x="22" y="12" width="16" height="5" rx="1" fill="#B8893F" opacity="0.6" />
                <path
                    d="M18 22 C8 32 7 48 7 58 C7 78 15 94 30 96 C45 94 53 78 53 58 C53 48 52 32 42 22 Z"
                    fill="#B8893F"
                    opacity="0.15"
                    stroke="#B8893F"
                    strokeWidth="0.8"
                />
                <path
                    d="M22 22 C15 32 14 46 14 55 C14 70 21 85 30 87 C39 85 46 70 46 55 C46 46 45 32 38 22 Z"
                    fill="#B8893F"
                    opacity="0.22"
                />
                <ellipse cx="30" cy="55" rx="10" ry="14" fill="#B8893F" opacity="0.08" />
            </svg>
        </div>
    );
}

function GarmentSilhouette({ color, kind = 'Punjabi' }: { color: string; kind?: Usage }) {
    const accent = 'rgba(0,0,0,.22)';
    const figure = 'rgba(43,54,64,.18)';
    const garment = kind === 'Ready-Made' ? 'Punjabi' : kind;

    return (
        <svg viewBox="0 0 200 240" className="h-full w-full" aria-hidden="true">
            <ellipse cx="100" cy="230" rx="48" ry="4" fill="rgba(0,0,0,.10)" />
            <circle cx="100" cy="34" r="14" fill={figure} />
            <path d="M92 46v10q8 6 16 0V46Z" fill={figure} />
            {garment === 'Punjabi' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v130H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 76l-4 54 14 2V90Z" fill={color} />
                    <path d="M130 60 148 76l4 54-14 2V90Z" fill={color} />
                    <line x1="100" y1="62" x2="100" y2="142" stroke={accent} strokeWidth="1.2" />
                    <path d="M88 56q12 8 24 0v-7q-12 5-24 0Z" fill={accent} opacity=".65" />
                    <rect x="62" y="210" width="76" height="10" fill="rgba(0,0,0,.10)" />
                </g>
            )}
            {garment === 'Shirt' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v80H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 80l-4 70 14 2V90Z" fill={color} />
                    <path d="M130 60 148 80l4 70-14 2V90Z" fill={color} />
                    <path d="M88 56 100 77l12-21v-7q-12 5-24 0Z" fill={accent} opacity=".65" />
                    <rect x="76" y="94" width="15" height="15" fill={accent} opacity=".35" />
                </g>
            )}
            {garment === 'Kabli' && (
                <g>
                    <path d="M70 60 92 56q8 14 16 0l22 4 8 30v90H62V90l8-30Z" fill={color} />
                    <path d="M70 60 52 78l-4 62 14 4V90Z" fill={color} />
                    <path d="M130 60 148 78l4 62-14 4V90Z" fill={color} />
                    <path d="M100 65 122 90v70h-22Z" fill="rgba(0,0,0,.06)" />
                    <path d="M70 180v50h26l4-46 4 46h26v-50Z" fill={color} opacity=".96" />
                </g>
            )}
        </svg>
    );
}

function CheckoutStepper() {
    const steps = ['Cart', 'Information', 'Shipping', 'Payment'];
    return (
        <div className="grid grid-cols-4 border border-[var(--brand-line)] bg-white/60">
            {steps.map((step, index) => (
                <div
                    key={step}
                    className={`flex items-center gap-2 border-r border-[var(--brand-line)] px-3 py-3 last:border-r-0 ${index === 0 ? 'bg-[var(--brand-slate)] text-[var(--brand-ivory)]' : 'text-[var(--brand-muted)]'}`}
                >
                    <span
                        className={`flex h-7 w-7 items-center justify-center rounded-full border text-[11px] ${index === 0 ? 'border-[var(--brand-gold)] text-[var(--brand-gold)]' : 'border-[var(--brand-line)]'}`}
                    >
                        {index + 1}
                    </span>
                    <span className="hidden text-xs font-medium sm:inline">{step}</span>
                </div>
            ))}
        </div>
    );
}

function EmptyCart() {
    const { t } = useLang();

    return (
        <FrontendLayout>
            <Head title={t.cart.title} />
            <div className="bg-[var(--brand-cream)] px-4 py-16">
                <div className="ornament-bg mx-auto max-w-4xl border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-8 text-center md:p-14">
                    <DiamondGlyph className="mx-auto h-14 w-14 text-[var(--brand-gold)]" />
                    <p className="eyebrow mt-6 text-[var(--brand-gold-dim)]">Your cart is empty</p>
                    <h1 className="font-display mt-3 text-5xl text-[var(--brand-ink)]">{t.cart.empty}</h1>
                    <p className="mx-auto mt-4 max-w-xl text-sm leading-7 text-[var(--brand-muted)]">{t.cart.emptySubtitle}</p>
                    <div className="mt-8 grid gap-3 sm:grid-cols-3">
                        {usageGuides.map((guide) => (
                            <Link
                                key={guide.type}
                                href={guide.href}
                                className="border border-[var(--brand-line)] bg-white px-4 py-5 text-left transition hover:border-[var(--brand-gold)]"
                            >
                                <span className="font-display text-2xl text-[var(--brand-ink)]">{guide.type}</span>
                                <span className="mt-1 block text-xs text-[var(--brand-gold-dim)]">{guide.length}</span>
                            </Link>
                        ))}
                    </div>
                    <Link
                        href="/products"
                        className="mt-8 inline-flex h-12 items-center justify-center bg-[var(--brand-slate)] px-7 text-sm font-semibold text-[var(--brand-ivory)] hover:bg-[var(--brand-ink)]"
                    >
                        {t.cart.shopNow}
                    </Link>
                </div>
            </div>
        </FrontendLayout>
    );
}

// ─── Fragrance Cart Item ──────────────────────────────────────────────────────

function FragranceCartItem({
    item,
    onUpdateQty,
    onRemove,
    onSave,
}: {
    item: CartItem;
    onUpdateQty: (rowId: string, qty: number) => void;
    onRemove: (rowId: string) => void;
    onSave: (item: CartItem) => void;
}) {
    return (
        <article
            className="border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-4 md:p-5"
            style={{ borderLeft: '3px solid rgba(184,137,63,0.4)' }}
        >
            <div className="grid gap-4 sm:grid-cols-[132px_1fr]">
                {/* Image */}
                <div>
                    <div className="aspect-[4/5] overflow-hidden border border-[var(--brand-line)] bg-[var(--brand-cream)]">
                        {item.image ? (
                            <img src={`/storage/${item.image}`} alt={item.name} className="h-full w-full object-cover" />
                        ) : (
                            <FragranceBottleFallback />
                        )}
                    </div>
                    <div
                        className="mt-2 px-2 py-1 text-center text-[10px] font-medium tracking-[0.12em] uppercase"
                        style={{ background: 'rgba(184,137,63,0.1)', color: '#B8893F' }}
                    >
                        Fragrance
                    </div>
                </div>

                {/* Info */}
                <div className="min-w-0">
                    <div className="flex items-start justify-between gap-4">
                        <div>
                            <h2 className="font-display text-2xl leading-tight text-[var(--brand-ink)] md:text-3xl">{item.name}</h2>
                            {item.variant_label && (
                                <p
                                    className="mt-1 inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs"
                                    style={{ borderColor: 'rgba(184,137,63,0.3)', color: '#B8893F', background: 'rgba(184,137,63,0.06)' }}
                                >
                                    <svg viewBox="0 0 20 20" fill="currentColor" style={{ width: '10px', opacity: 0.7 }}>
                                        <path d="M10 2L12 8L18 10L12 12L10 18L8 12L2 10L8 8Z" />
                                    </svg>
                                    {item.variant_label}
                                </p>
                            )}
                        </div>
                        <button
                            onClick={() => onRemove(item.row_id)}
                            className="text-[var(--brand-muted)] transition hover:text-[#8E3B2E]"
                            aria-label={`Remove ${item.name}`}
                        >
                            <X size={18} />
                        </button>
                    </div>

                    <div className="mt-5 flex flex-wrap items-end justify-between gap-4">
                        <div className="flex items-center border border-[var(--brand-line)] bg-white">
                            <button
                                onClick={() => onUpdateQty(item.row_id, item.qty - 1)}
                                disabled={item.qty <= 1}
                                className="flex h-10 w-10 items-center justify-center text-[var(--brand-muted)] hover:bg-[var(--brand-cream)] disabled:opacity-35"
                                aria-label="Decrease quantity"
                            >
                                <Minus size={14} />
                            </button>
                            <span className="w-10 text-center text-sm font-semibold">{item.qty}</span>
                            <button
                                onClick={() => onUpdateQty(item.row_id, item.qty + 1)}
                                className="flex h-10 w-10 items-center justify-center text-[var(--brand-muted)] hover:bg-[var(--brand-cream)]"
                                aria-label="Increase quantity"
                            >
                                <Plus size={14} />
                            </button>
                        </div>

                        <div className="text-right">
                            <div className="text-xs text-[var(--brand-muted)]">{formatMoney(item.price)} each</div>
                            <div className="font-display text-3xl text-[var(--brand-ink)]">{formatMoney(item.price * item.qty)}</div>
                        </div>
                    </div>

                    <div className="mt-4 flex flex-wrap gap-4 text-xs">
                        <button onClick={() => onSave(item)} className="link-gold text-[var(--brand-muted)]">
                            Save for later
                        </button>
                        <button onClick={() => onRemove(item.row_id)} className="text-[#8E3B2E] hover:underline">
                            Remove
                        </button>
                    </div>
                </div>
            </div>
        </article>
    );
}

// ─── Fabric / Cloth Cart Item ─────────────────────────────────────────────────

function FabricCartItem({
    item,
    onUpdateQty,
    onRemove,
    onSave,
}: {
    item: CartItem;
    onUpdateQty: (rowId: string, qty: number) => void;
    onRemove: (rowId: string) => void;
    onSave: (item: CartItem) => void;
}) {
    const usage = inferUsage(item);
    const length = inferLength(usage);
    const color = inferColor(item);
    const isReadyMade = usage === 'Ready-Made';

    return (
        <article className="border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-4 md:p-5">
            <div className="grid gap-4 sm:grid-cols-[132px_1fr]">
                <div>
                    <div className="aspect-[4/5] overflow-hidden border border-[var(--brand-line)] bg-[var(--brand-cream)]">
                        {item.image ? (
                            <img src={`/storage/${item.image}`} alt={item.name} className="h-full w-full object-cover" />
                        ) : isReadyMade ? (
                            <GarmentSilhouette color={color.hex} kind={usage} />
                        ) : (
                            <FabricTexture color={color.hex} label="fabric" />
                        )}
                    </div>
                    <div className="mt-2 bg-[var(--brand-slate)] px-2 py-1 text-center text-[10px] font-medium text-[var(--brand-ivory)]">
                        {isReadyMade ? 'Ready-made' : `As ${usage}`}
                    </div>
                </div>

                <div className="min-w-0">
                    <div className="flex items-start justify-between gap-4">
                        <div>
                            <h2 className="font-display text-2xl leading-tight text-[var(--brand-ink)] md:text-3xl">{item.name}</h2>
                            <p className="mt-1 text-xs text-[var(--brand-muted)]">{item.variant_label ?? 'Premium modest wear selection'}</p>
                        </div>
                        <button
                            onClick={() => onRemove(item.row_id)}
                            className="text-[var(--brand-muted)] transition hover:text-[#8E3B2E]"
                            aria-label={`Remove ${item.name}`}
                        >
                            <X size={18} />
                        </button>
                    </div>

                    <div className="mt-4 flex flex-wrap gap-2">
                        <span className="inline-flex items-center gap-2 border border-[var(--brand-line)] bg-white px-3 py-2 text-xs text-[var(--brand-muted)]">
                            <span className="h-3 w-3 rounded-full border border-black/10" style={{ backgroundColor: color.hex }} />
                            {color.name}
                        </span>
                        <span className="inline-flex items-center gap-2 border border-[var(--brand-line)] bg-white px-3 py-2 text-xs text-[var(--brand-muted)]">
                            <ShoppingBag size={13} className="text-[var(--brand-gold)]" />
                            Use as {usage}
                        </span>
                        <span className="inline-flex items-center gap-2 border border-[var(--brand-gold)] bg-white px-3 py-2 text-xs font-medium text-[var(--brand-gold-dim)]">
                            <Ruler size={13} />
                            {length}
                        </span>
                    </div>

                    <div className="mt-5 flex flex-wrap items-end justify-between gap-4">
                        <div className="flex items-center border border-[var(--brand-line)] bg-white">
                            <button
                                onClick={() => onUpdateQty(item.row_id, item.qty - 1)}
                                disabled={item.qty <= 1}
                                className="flex h-10 w-10 items-center justify-center text-[var(--brand-muted)] hover:bg-[var(--brand-cream)] disabled:opacity-35"
                                aria-label="Decrease quantity"
                            >
                                <Minus size={14} />
                            </button>
                            <span className="w-10 text-center text-sm font-semibold">{item.qty}</span>
                            <button
                                onClick={() => onUpdateQty(item.row_id, item.qty + 1)}
                                className="flex h-10 w-10 items-center justify-center text-[var(--brand-muted)] hover:bg-[var(--brand-cream)]"
                                aria-label="Increase quantity"
                            >
                                <Plus size={14} />
                            </button>
                        </div>

                        <div className="text-right">
                            <div className="text-xs text-[var(--brand-muted)]">{formatMoney(item.price)} each</div>
                            <div className="font-display text-3xl text-[var(--brand-ink)]">{formatMoney(item.price * item.qty)}</div>
                        </div>
                    </div>

                    <div className="mt-4 flex flex-wrap gap-4 text-xs">
                        <button className="link-gold text-[var(--brand-gold-dim)]">Edit options</button>
                        <button onClick={() => onSave(item)} className="link-gold text-[var(--brand-muted)]">
                            Save for later
                        </button>
                        <button onClick={() => onRemove(item.row_id)} className="text-[#8E3B2E] hover:underline">
                            Remove
                        </button>
                    </div>
                </div>
            </div>
        </article>
    );
}

// ─── Cart Item Router ─────────────────────────────────────────────────────────

function CartItemCard({
    item,
    onUpdateQty,
    onRemove,
    onSave,
}: {
    item: CartItem;
    onUpdateQty: (rowId: string, qty: number) => void;
    onRemove: (rowId: string) => void;
    onSave: (item: CartItem) => void;
}) {
    if (item.product_type === 'fragrance') {
        return <FragranceCartItem item={item} onUpdateQty={onUpdateQty} onRemove={onRemove} onSave={onSave} />;
    }
    return <FabricCartItem item={item} onUpdateQty={onUpdateQty} onRemove={onRemove} onSave={onSave} />;
}

function CouponBox({
    totals,
    coupon,
    setCoupon,
    couponMsg,
    applying,
    onApply,
    onRemove,
}: {
    totals: CartTotals;
    coupon: string;
    setCoupon: (value: string) => void;
    couponMsg: string;
    applying: boolean;
    onApply: () => void;
    onRemove: () => void;
}) {
    const { t } = useLang();
    const [showCodes, setShowCodes] = useState(false);

    return (
        <section className="border border-[var(--brand-line)] bg-white p-5">
            <button onClick={() => setShowCodes((value) => !value)} className="mb-4 flex w-full items-center justify-between gap-3 text-left">
                <span className="flex items-center gap-2 text-sm font-semibold text-[var(--brand-ink)]">
                    <Tag size={16} className="text-[var(--brand-gold)]" />
                    {t.cart.couponCode}
                </span>
                <ChevronDown size={16} className={`text-[var(--brand-gold)] transition ${showCodes ? 'rotate-180' : ''}`} />
            </button>

            {totals.coupon_code ? (
                <div className="flex items-center justify-between bg-[#4A7A4A]/10 px-3 py-3">
                    <span className="font-mono text-sm font-semibold text-[#4A7A4A]">{totals.coupon_code}</span>
                    <button onClick={onRemove} className="text-[#4A7A4A] hover:text-[#8E3B2E]" aria-label="Remove coupon">
                        <X size={15} />
                    </button>
                </div>
            ) : (
                <div className="flex gap-2">
                    <input
                        value={coupon}
                        onChange={(event) => setCoupon(event.target.value)}
                        placeholder={t.cart.enterCode}
                        className="min-w-0 flex-1 border border-[var(--brand-line)] bg-[var(--brand-ivory)] px-3 py-2 text-sm outline-none focus:border-[var(--brand-gold)]"
                    />
                    <button
                        onClick={onApply}
                        disabled={applying}
                        className="bg-[var(--brand-slate)] px-4 py-2 text-sm font-semibold text-[var(--brand-ivory)] disabled:opacity-50"
                    >
                        {applying ? '...' : t.cart.apply}
                    </button>
                </div>
            )}

            {couponMsg && (
                <p className={`mt-2 text-xs ${couponMsg.toLowerCase().includes('applied') ? 'text-[#4A7A4A]' : 'text-[#8E3B2E]'}`}>{couponMsg}</p>
            )}

            {showCodes && (
                <div className="mt-4 grid gap-2 text-xs text-[var(--brand-muted)]">
                    {['WELCOME10', 'EID2026', 'ATELIER5'].map((code) => (
                        <button
                            key={code}
                            onClick={() => setCoupon(code)}
                            className="flex items-center justify-between border border-[var(--brand-line)] px-3 py-2 text-left hover:border-[var(--brand-gold)]"
                        >
                            <span className="font-mono text-[var(--brand-ink)]">{code}</span>
                            <span>Try code</span>
                        </button>
                    ))}
                </div>
            )}
        </section>
    );
}

function OrderSummary({ totals, count }: { totals: CartTotals; count: number }) {
    const { t } = useLang();

    return (
        <section className="sticky top-24 border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-5 shadow-[0_30px_80px_-60px_rgba(0,0,0,.45)]">
            <p className="eyebrow text-[var(--brand-gold-dim)]">{t.cart.orderSummary}</p>
            <h2 className="font-display mt-2 text-4xl text-[var(--brand-ink)]">{formatMoney(totals.total)}</h2>
            <p className="mt-1 text-xs text-[var(--brand-muted)]">
                {count} {t.cart.items} in your cart
            </p>

            <div className="mt-6 space-y-3 text-sm">
                <div className="flex justify-between">
                    <span className="text-[var(--brand-muted)]">{t.cart.subtotal}</span>
                    <span>{formatMoney(totals.subtotal)}</span>
                </div>
                {totals.discount > 0 && (
                    <div className="flex justify-between text-[#4A7A4A]">
                        <span>{t.cart.discount}</span>
                        <span>-{formatMoney(totals.discount)}</span>
                    </div>
                )}
                <div className="flex justify-between">
                    <span className="text-[var(--brand-muted)]">{t.cart.shipping}</span>
                    <span>{totals.shipping > 0 ? formatMoney(totals.shipping) : <span className="text-[#4A7A4A]">{t.common.free}</span>}</span>
                </div>
                <div className="flex justify-between border-t border-[var(--brand-line)] pt-4 text-base font-semibold">
                    <span>{t.cart.total}</span>
                    <span>{formatMoney(totals.total)}</span>
                </div>
            </div>

            <Link
                href="/checkout"
                className="mt-6 flex h-12 w-full items-center justify-center bg-[var(--brand-slate)] text-sm font-semibold text-[var(--brand-ivory)] hover:bg-[var(--brand-ink)]"
            >
                {t.cart.proceedToCheckout}
            </Link>
            <Link href="/products" className="mt-3 block text-center text-xs text-[var(--brand-muted)] hover:text-[var(--brand-gold-dim)]">
                {t.common.continueShopping}
            </Link>

            <div className="mt-5 grid grid-cols-4 gap-2 text-center text-[10px] font-semibold text-[var(--brand-muted)]">
                {['VISA', 'MC', 'AMEX', 'COD'].map((method) => (
                    <span key={method} className="border border-[var(--brand-line)] bg-white py-2">
                        {method}
                    </span>
                ))}
            </div>
            <p className="mt-4 flex items-center gap-2 text-xs text-[var(--brand-muted)]">
                <ShieldCheck size={15} className="text-[var(--brand-gold)]" />
                Secure checkout and carefully packed delivery.
            </p>
        </section>
    );
}

function FabricReminder() {
    return (
        <section className="border border-[var(--brand-line)] bg-[var(--brand-slate)] p-5 text-[var(--brand-ivory)] md:p-7">
            <div className="grid gap-6 md:grid-cols-[1fr_2fr] md:items-center">
                <div>
                    <p className="eyebrow text-[var(--brand-gold)]">Fabric reminder</p>
                    <h2 className="font-display mt-2 text-4xl">Check length before tailoring</h2>
                    <p className="mt-3 text-sm leading-7 text-white/65">Use these yardage ranges as a quick planning guide before checkout.</p>
                </div>
                <div className="grid gap-3 sm:grid-cols-3">
                    {usageGuides.map((guide) => (
                        <Link
                            key={guide.type}
                            href={guide.href}
                            className="border border-white/10 bg-white/[0.04] p-4 transition hover:border-[var(--brand-gold)]"
                        >
                            <div className="font-display text-2xl">{guide.type}</div>
                            <div className="mt-1 text-sm text-[var(--brand-gold)]">{guide.length}</div>
                        </Link>
                    ))}
                </div>
            </div>
        </section>
    );
}

function RecommendedProducts() {
    return (
        <section>
            <div className="mb-5 flex items-end justify-between gap-4">
                <div>
                    <p className="eyebrow text-[var(--brand-gold-dim)]">Recommended</p>
                    <h2 className="font-display mt-2 text-4xl text-[var(--brand-ink)]">Complete the outfit</h2>
                </div>
                <Link href="/products" className="link-gold hidden text-sm text-[var(--brand-gold-dim)] sm:block">
                    View all
                </Link>
            </div>
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                {recommended.map((item) => (
                    <Link key={item.name} href="/products" className="group">
                        <div className="aspect-[4/5] overflow-hidden border border-[var(--brand-line)] bg-[var(--brand-ivory)]">
                            <FabricTexture color={item.color} label="fabric" />
                        </div>
                        <div className="mt-3 line-clamp-2 text-sm text-[var(--brand-ink)] group-hover:text-[var(--brand-gold-dim)]">{item.name}</div>
                        <div className="font-display text-2xl text-[var(--brand-ink)]">{formatMoney(item.price)}</div>
                    </Link>
                ))}
            </div>
        </section>
    );
}

export default function CartIndex({ items, totals }: { items: CartItem[]; totals: CartTotals }) {
    const { t } = useLang();
    const [coupon, setCoupon] = useState(totals.coupon_code ?? '');
    const [couponMsg, setCouponMsg] = useState('');
    const [applying, setApplying] = useState(false);
    const [savedItems, setSavedItems] = useState<CartItem[]>([]);

    const itemCount = useMemo(() => items.reduce((sum, item) => sum + item.qty, 0), [items]);
    const hasFabricItems = useMemo(() => items.some((item) => item.product_type !== 'fragrance'), [items]);
    const csrf = () => xsrfToken();

    const updateQty = async (rowId: string, qty: number) => {
        if (qty < 1) { return; }
        await fetch(`/cart/update/${encodeURIComponent(rowId)}`, {
            method: 'PATCH',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': csrf() },
            body: JSON.stringify({ qty }),
        });
        router.reload({ preserveState: true });
    };

    const removeItem = async (rowId: string) => {
        await fetch(`/cart/remove/${encodeURIComponent(rowId)}`, {
            method: 'DELETE',
            credentials: 'same-origin',
            headers: { 'X-XSRF-TOKEN': csrf() },
        });
        router.reload({ preserveState: true });
    };

    const clearCart = async () => {
        await fetch('/cart/clear', { method: 'DELETE', credentials: 'same-origin', headers: { 'X-XSRF-TOKEN': csrf() } });
        router.reload({ preserveState: true });
    };

    const saveForLater = (item: CartItem) => {
        setSavedItems((current) => (current.some((saved) => saved.row_id === item.row_id) ? current : [...current, item]));
    };

    const applyCoupon = async () => {
        if (!coupon.trim()) { return; }
        setApplying(true);
        setCouponMsg('');
        try {
            const response = await fetch('/cart/coupon', {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': csrf() },
                body: JSON.stringify({ code: coupon }),
            });
            const json = await response.json();
            setCouponMsg(json.message ?? (json.valid ? t.cart.couponApplied : t.cart.invalidCoupon));
            if (json.valid) { router.reload({ preserveState: true }); }
        } catch {
            setCouponMsg(t.cart.couponFailed);
        } finally {
            setApplying(false);
        }
    };

    const removeCoupon = async () => {
        await fetch('/cart/coupon', {
            method: 'DELETE',
            credentials: 'same-origin',
            headers: { 'X-XSRF-TOKEN': csrf(), 'Content-Type': 'application/json' },
        });
        setCoupon('');
        setCouponMsg('');
        router.reload({ preserveState: true });
    };

    if (!items.length) { return <EmptyCart />; }

    const heroSubtitle = hasFabricItems
        ? 'Confirm usage, fabric length, quantity, and delivery details before checkout.'
        : 'Review your fragrance selection and delivery details before checkout.';

    return (
        <FrontendLayout>
            <Head title={t.cart.title} />

            <div className="bg-[var(--brand-cream)] text-[var(--brand-ink)]">
                <section className="ornament-bg border-b border-[var(--brand-line)] bg-[var(--brand-ivory)]">
                    <div className="mx-auto max-w-[1500px] px-4 py-10 sm:px-6 lg:px-10 lg:py-14">
                        <nav className="eyebrow mb-6 flex items-center gap-2 text-[var(--brand-muted)]">
                            <Link href="/" className="hover:text-[var(--brand-gold-dim)]">
                                Home
                            </Link>
                            <span>/</span>
                            <span className="text-[var(--brand-ink)]">{t.cart.title}</span>
                        </nav>
                        <div className="grid gap-7 lg:grid-cols-[1fr_460px] lg:items-end">
                            <div>
                                <p className="eyebrow mb-3 text-[var(--brand-gold-dim)]">Review your selection</p>
                                <h1 className="font-display text-5xl leading-[0.95] text-[var(--brand-ink)] md:text-7xl">{t.cart.title}</h1>
                                <p className="mt-4 max-w-2xl text-sm leading-7 text-[var(--brand-muted)]">{heroSubtitle}</p>
                            </div>
                            <CheckoutStepper />
                        </div>
                    </div>
                </section>

                <main className="mx-auto max-w-[1500px] px-4 py-8 sm:px-6 lg:px-10 lg:py-12">
                    <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_390px]">
                        <div className="space-y-5">
                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <div>
                                    <p className="eyebrow text-[var(--brand-gold-dim)]">
                                        {items.length} {t.cart.items}
                                    </p>
                                    <h2 className="font-display mt-1 text-4xl text-[var(--brand-ink)]">Cart items</h2>
                                </div>
                                <button onClick={clearCart} className="inline-flex items-center gap-2 text-xs text-[#8E3B2E] hover:underline">
                                    <Trash2 size={14} />
                                    {t.cart.clearAll}
                                </button>
                            </div>

                            {items.map((item) => (
                                <CartItemCard key={item.row_id} item={item} onUpdateQty={updateQty} onRemove={removeItem} onSave={saveForLater} />
                            ))}

                            {savedItems.length > 0 && (
                                <section className="border border-[var(--brand-line)] bg-white p-5">
                                    <p className="eyebrow text-[var(--brand-gold-dim)]">Saved for later</p>
                                    <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                        {savedItems.map((item) => (
                                            <div
                                                key={item.row_id}
                                                className="flex items-center justify-between gap-3 border border-[var(--brand-line)] px-3 py-3 text-sm"
                                            >
                                                <span className="line-clamp-1">{item.name}</span>
                                                <button
                                                    onClick={() =>
                                                        setSavedItems((current) => current.filter((saved) => saved.row_id !== item.row_id))
                                                    }
                                                    className="text-[var(--brand-gold-dim)]"
                                                >
                                                    Remove
                                                </button>
                                            </div>
                                        ))}
                                    </div>
                                </section>
                            )}

                            {hasFabricItems && <FabricReminder />}
                            {hasFabricItems && <RecommendedProducts />}
                        </div>

                        <aside className="space-y-4">
                            <OrderSummary totals={totals} count={itemCount} />
                            <CouponBox
                                totals={totals}
                                coupon={coupon}
                                setCoupon={setCoupon}
                                couponMsg={couponMsg}
                                applying={applying}
                                onApply={applyCoupon}
                                onRemove={removeCoupon}
                            />

                            <section className="grid gap-3 border border-[var(--brand-line)] bg-white p-5 text-xs text-[var(--brand-muted)]">
                                <div className="flex items-center gap-2">
                                    <PackageCheck size={16} className="text-[var(--brand-gold)]" />
                                    Carefully packed before delivery
                                </div>
                                <div className="flex items-center gap-2">
                                    <Truck size={16} className="text-[var(--brand-gold)]" />
                                    Delivery estimate shared after confirmation
                                </div>
                                <div className="flex items-center gap-2">
                                    <Check size={16} className="text-[var(--brand-gold)]" />
                                    {hasFabricItems ? 'Fabric guide checked before checkout' : 'Authentic products, verified before dispatch'}
                                </div>
                            </section>
                        </aside>
                    </div>
                </main>

                <div className="fixed inset-x-0 bottom-0 z-40 border-t border-[var(--brand-line)] bg-[var(--brand-ivory)] p-3 shadow-[0_-18px_40px_-28px_rgba(0,0,0,.45)] lg:hidden">
                    <div className="mx-auto flex max-w-[1500px] items-center gap-3">
                        <div className="min-w-0 flex-1">
                            <div className="text-[10px] tracking-[0.18em] text-[var(--brand-muted)] uppercase">{t.cart.total}</div>
                            <div className="font-display text-2xl text-[var(--brand-ink)]">{formatMoney(totals.total)}</div>
                        </div>
                        <Link
                            href="/checkout"
                            className="flex h-11 items-center justify-center bg-[var(--brand-slate)] px-5 text-sm font-semibold text-[var(--brand-ivory)]"
                        >
                            Checkout
                        </Link>
                    </div>
                </div>
            </div>
        </FrontendLayout>
    );
}
