import { Button } from '@/Components/ui';
import type { KitGridSection as Data } from '@/marketing/cms-types';
import { SanitizedHtmlBody, SanitizedHtmlInline } from '@/marketing/sanitized-html';
import { CrossMark, Reveal, useKitCta } from '@/marketing/shared';
import { Link, router } from '@inertiajs/react';
import { ArrowRight } from 'lucide-react';
import type { ReactNode } from 'react';

/* Kit shape comes from the server (TemplatesController) which reads kit
 * JSON files from `resources/templates/projects/{key}/{key}.json`. Each
 * screen has a `preview_path` pointing at an image served from `public/`.
 * No inline JSX mockups — screens render as `<img>` tags. */

export type KitScreen = {
    name: string;
    preview_path: string;
};

export type KitMeta = {
    key: string;
    name: string;
    category: string;
    tagline: string;
    description: string;
    screen_count: number;
    is_featured: boolean;
    is_premium: boolean;
    screens: KitScreen[];
};

export type KitPagination = {
    total: number;
    offset: number;
    limit: number;
    has_more: boolean;
};

export type KitFilter = {
    category: string | null;
    categories: string[];
};

type Props = {
    section: Data;
    featured: KitMeta | null;
    kits: KitMeta[];
    pagination: KitPagination;
    filter: KitFilter;
    showRails?: boolean;
};

/**
 * Real renderer for the mandatory `kit_grid` section on /templates. Owns
 * three subsections: optional heading/subhead, the featured-kit hero strip
 * (when a featured kit exists), and the filter-chips + paginated kit grid.
 * Featured-kit selection happens server-side (TemplatesController honors
 * `section.featuredKitKey` first, falling back to the kit JSON's own
 * `is_featured` flag) — the renderer just trusts the `featured` prop.
 */
export function KitGridSectionRenderer({
    section,
    featured,
    kits,
    pagination,
    filter,
    showRails = true,
}: Props) {
    return (
        <>
            {(section.eyebrow || section.heading || section.subhead) && (
                <KitGridHeader section={section} showRails={showRails} />
            )}
            {featured && <FeaturedKit meta={featured} showRails={showRails} />}
            <KitGrid
                section={section}
                kits={kits}
                pagination={pagination}
                filter={filter}
                showRails={showRails}
            />
        </>
    );
}

/* ──────────────────────────────────────────────── Heading strip ── */

function KitGridHeader({
    section,
    showRails,
}: {
    section: Data;
    showRails: boolean;
}) {
    return (
        <section className="ms-section-kits border-t border-border/60">
            <RailsContainer showRails={showRails} className="py-16 lg:py-20">
                <Reveal>
                    <div className="ms-head max-w-3xl">
                        {section.eyebrow && (
                            <div className="ms-badge mb-6 inline-flex items-center rounded-full bg-accent px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-accent-foreground">
                                <SanitizedHtmlInline html={section.eyebrow} />
                            </div>
                        )}
                        {section.heading && (
                            <h2 className="font-display text-3xl font-medium leading-[1.1] tracking-tight text-foreground sm:text-4xl [&_em]:font-display [&_em]:italic [&_em]:text-accent lg:text-5xl">
                                <SanitizedHtmlInline html={section.heading} />
                            </h2>
                        )}
                        {section.subhead && (
                            <SanitizedHtmlBody
                                html={section.subhead}
                                className="mt-5 text-lg"
                            />
                        )}
                    </div>
                </Reveal>
            </RailsContainer>
        </section>
    );
}

/* ──────────────────────────────────────────────── Featured kit ── */

function FeaturedKit({
    meta,
    showRails,
}: {
    meta: KitMeta;
    showRails: boolean;
}) {
    const cta = useKitCta(meta);
    return (
        <section className="ms-featured ms-section-kits border-t border-border/60 bg-card/40">
            <RailsContainer showRails={showRails} className="py-20 lg:py-28">
                <Reveal>
                    <div className="max-w-3xl">
                        <p className="text-xs font-medium uppercase tracking-wider text-accent">
                            Featured kit · {meta.category}
                        </p>
                        <h2 className="mt-4 font-display text-3xl font-medium leading-[1.1] tracking-tight text-foreground sm:text-4xl lg:text-5xl">
                            {meta.name}
                            {meta.is_premium && (
                                <span className="ml-3 inline-flex items-center rounded-full bg-accent/10 px-2.5 py-1 align-middle text-xs font-semibold uppercase tracking-wider text-accent">
                                    Pro
                                </span>
                            )}
                        </h2>
                        <p className="mt-5 text-lg leading-relaxed text-muted-foreground">
                            {meta.description}
                        </p>
                        <div className="mt-8 flex flex-wrap items-center gap-4">
                            <Link
                                href={cta.href}
                                onClick={cta.onClick}
                                data-testid={`marketing-kit-cta-${meta.key}`}
                            >
                                <Button size="lg">
                                    Use this kit
                                    <ArrowRight className="h-4 w-4" />
                                </Button>
                            </Link>
                            <span className="text-sm text-muted-foreground">
                                {meta.screen_count} screens · 8 device sizes
                            </span>
                        </div>
                    </div>
                </Reveal>
                <Reveal delay={0.12}>
                    <div className="-mx-6 mt-14 overflow-x-auto pb-4 lg:-mx-8">
                        <div className="flex gap-5 px-6 lg:px-8">
                            {meta.screens.map((screen, idx) => (
                                <div
                                    key={idx}
                                    className="flex shrink-0 flex-col items-center"
                                >
                                    <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                        {screen.name}
                                    </p>
                                    <img
                                        src={screen.preview_path}
                                        alt={`${meta.name} — ${screen.name}`}
                                        loading="lazy"
                                        className="mt-3 h-[420px] w-[194px] rounded-[1.5rem] border-[8px] border-foreground bg-foreground object-cover shadow-xl"
                                    />
                                </div>
                            ))}
                        </div>
                    </div>
                </Reveal>
            </RailsContainer>
            {cta.modal}
        </section>
    );
}

/* ──────────────────────────────────────────────────── Kit grid ── */

function KitGrid({
    section,
    kits,
    pagination,
    filter,
    showRails,
}: {
    section: Data;
    kits: KitMeta[];
    pagination: KitPagination;
    filter: KitFilter;
    showRails: boolean;
}) {
    const setCategory = (category: string | null) => {
        const params: Record<string, string> = {};
        if (category) params.category = category;
        router.get('/templates', params, {
            preserveScroll: true,
            preserveState: false,
        });
    };

    const loadMore = () => {
        const params: Record<string, string | number> = {
            offset: pagination.offset + pagination.limit,
            limit: pagination.limit,
        };
        if (filter.category) params.category = filter.category;
        router.get('/templates', params, {
            preserveScroll: true,
            preserveState: false,
        });
    };

    // The "show chips" decision combines admin intent (`showCategories`)
    // with data presence: a single-category install would surface a
    // pointless "All / X" toggle even with the admin toggle on.
    const showChips =
        section.showCategories !== false && filter.categories.length >= 2;

    return (
        <section className="ms-section-kits border-t border-border/60">
            <RailsContainer showRails={showRails} className="py-24 lg:py-24">
                {showChips && (
                    <Reveal delay={0.05}>
                        <div className="flex flex-wrap gap-2">
                            <FilterChip
                                active={filter.category === null}
                                onClick={() => setCategory(null)}
                            >
                                All
                            </FilterChip>
                            {filter.categories.map((cat) => (
                                <FilterChip
                                    key={cat}
                                    active={filter.category === cat}
                                    onClick={() => setCategory(cat)}
                                >
                                    {cat}
                                </FilterChip>
                            ))}
                        </div>
                    </Reveal>
                )}

                <Reveal delay={0.1}>
                    {kits.length === 0 ? (
                        <div className={`${showChips ? 'mt-16' : ''} rounded-2xl border border-border bg-card/40 p-10 text-center`}>
                            <p className="font-display text-lg font-semibold text-foreground">
                                No kits in this category yet.
                            </p>
                            <p className="mt-2 text-sm text-muted-foreground">
                                Try a different filter, or browse all kits.
                            </p>
                            <button
                                type="button"
                                onClick={() => setCategory(null)}
                                className="mt-6 inline-flex items-center gap-1 text-sm font-medium text-accent transition-opacity hover:opacity-80"
                            >
                                Browse all kits
                                <ArrowRight className="h-3.5 w-3.5" />
                            </button>
                        </div>
                    ) : (
                        <div className={`-mx-6 ${showChips ? 'mt-12' : ''} divide-y divide-border/60 border-y border-border/60 lg:-mx-8`}>
                            {kits.map((kit) => (
                                <KitCard
                                    key={kit.key}
                                    meta={kit}
                                    showScreenCount={section.showScreenCount !== false}
                                />
                            ))}
                        </div>
                    )}
                </Reveal>

                {pagination.has_more && (
                    <Reveal delay={0.05}>
                        <div className="mt-10 text-center">
                            <Button
                                variant="secondary"
                                size="md"
                                onClick={loadMore}
                            >
                                Load more kits
                                <ArrowRight className="h-4 w-4" />
                            </Button>
                            <p className="mt-3 text-xs text-muted-foreground">
                                Showing {pagination.offset + kits.length} of{' '}
                                {pagination.total}
                            </p>
                        </div>
                    </Reveal>
                )}
            </RailsContainer>
        </section>
    );
}

function FilterChip({
    children,
    active,
    onClick,
}: {
    children: ReactNode;
    active: boolean;
    onClick: () => void;
}) {
    return (
        <button
            type="button"
            onClick={onClick}
            className={`ms-chip rounded-full border px-4 py-1.5 text-sm font-medium transition-all ${
                active
                    ? 'border-foreground bg-foreground text-background'
                    : 'border-border bg-card text-muted-foreground hover:border-foreground/30 hover:text-foreground'
            }`}
        >
            {children}
        </button>
    );
}

function KitCard({
    meta,
    showScreenCount,
}: {
    meta: KitMeta;
    showScreenCount: boolean;
}) {
    const cta = useKitCta(meta);
    return (
        <>
        <Link
            href={cta.href}
            onClick={cta.onClick}
            data-testid={`marketing-kit-card-${meta.key}`}
            data-premium={meta.is_premium ? 'true' : undefined}
            className="ms-card group flex flex-col gap-8 bg-card p-8 transition-colors hover:bg-background lg:flex-row lg:items-center lg:gap-10 lg:p-10"
        >
            <div className="flex-1 min-w-0 lg:max-w-md">
                <div className="flex flex-wrap items-center gap-2 text-xs uppercase tracking-wider text-muted-foreground">
                    <span>{meta.category}</span>
                    {meta.is_premium && (
                        <span className="inline-flex items-center rounded-full bg-accent/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-accent">
                            Pro
                        </span>
                    )}
                </div>
                <h3 className="mt-2 font-display text-2xl font-semibold text-foreground transition-colors group-hover:text-accent">
                    {meta.name}
                </h3>
                <p className="mt-3 text-sm leading-relaxed text-muted-foreground">
                    {meta.tagline}
                </p>
                <div className="mt-5 flex items-center justify-between gap-3 text-xs text-muted-foreground">
                    <span>
                        {showScreenCount
                            ? `${meta.screen_count} screens · 8 device sizes`
                            : '8 device sizes'}
                    </span>
                    <span className="inline-flex shrink-0 items-center gap-1 text-sm font-medium text-accent transition-opacity group-hover:opacity-80">
                        Use this kit
                        <ArrowRight className="h-3.5 w-3.5" />
                    </span>
                </div>
            </div>
            <div className="-mx-4 overflow-x-auto pb-1 lg:mx-0 lg:flex-1">
                <div className="flex items-end gap-3 px-4 lg:px-0">
                    {meta.screens.map((screen, idx) => (
                        <img
                            key={idx}
                            src={screen.preview_path}
                            alt={`${meta.name} — ${screen.name}`}
                            loading="lazy"
                            className="h-[180px] w-[83px] shrink-0 rounded-[14px] border-[3px] border-foreground bg-foreground object-cover shadow-md"
                        />
                    ))}
                </div>
            </div>
        </Link>
        {cta.modal}
        </>
    );
}

/* Shared rails wrapper — `showRails` toggles the side borders + crosshair
 * markers so the section sits flush when AppNav chrome is mounted (authed
 * user in non-landing-mode) and gets full marketing-rails treatment in the
 * default public render. */
function RailsContainer({
    children,
    showRails,
    className = '',
}: {
    children: ReactNode;
    showRails: boolean;
    className?: string;
}) {
    return (
        <div
            className={
                'relative mx-auto max-w-6xl px-6 lg:px-8 ' +
                (showRails ? 'border-x border-border/60 ' : '') +
                className
            }
        >
            {showRails && <CrossMark className="left-0 top-0" />}
            {showRails && <CrossMark className="left-full top-0" />}
            {children}
        </div>
    );
}
