import { Fragment, useState } from 'react';
import { AtlasArt } from '@/site/components/art/atlas-art';
import { CategoryIcon } from '@/site/components/art/category-icon';
import { Reveal } from '@/site/components/motion/reveal';
import { CtaBand } from '@/site/components/sections/cta-band';
import { PageHero, sheet } from '@/site/components/sections/page-hero';
import { ButtonLink } from '@/site/components/ui/button';
import { ArrowUpRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { Term } from '@/site/components/ui/term';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { CategoryWithTreatments, Stats } from '@/site/types';

type IndexArea = CategoryWithTreatments & {
    /** The named group it belongs to (a department of several areas, the other areas), if any. */
    group: string | null;
};

type IndexGroup = { key: string; name: string; tagline: string | null };

type TreatmentsIndexProps = {
    /** Every area, department by department. */
    categories: IndexArea[];
    /** The named groups, with their headings. */
    groups: IndexGroup[];
    stats: Stats;
};

const two = (value: number) => String(value).padStart(2, '0');

/** Consecutive areas of the same named group; an area outside every group stands alone. */
function runs(categories: IndexArea[], groups: IndexGroup[]) {
    const result: { group: IndexGroup | null; areas: IndexArea[] }[] = [];

    for (const area of categories) {
        const last = result.at(-1);

        if (area.group !== null && last?.group?.key === area.group) {
            last.areas.push(area);

            continue;
        }

        result.push({
            group: groups.find((group) => group.key === area.group) ?? null,
            areas: [area],
        });
    }

    return result;
}

/**
 * Hub of all treatments: every area of expertise with all of its
 * treatments on one page, each linking to its own page. The areas follow
 * the departments (docs/DECISIONS.md K37). A department of several areas
 * (medical aesthetics) and the other areas are each a tinted block that
 * opens with its heading, so where a group ends is as plain as where it
 * begins — men's health after medical aesthetics stands on its own. The
 * home page links to the block of medical aesthetics (#aesthetics).
 */
export default function TreatmentsIndex({
    categories,
    groups,
    stats,
}: TreatmentsIndexProps) {
    const t = useT();
    // The area under the pointer: its jump link and its mark in the drawing light up together.
    const [pointed, setPointed] = useState<string | null>(null);
    // Each area's running number on the page (01 / 11…).
    const order = new Map(
        categories.map((category, index) => [category.key, index + 1]),
    );

    return (
        <>
            <PageHero
                eyebrow={t.treatments.eyebrow}
                title={t.treatments.title}
                lead={t.treatments.lead(stats.categories, stats.treatments)}
                art={
                    <AtlasArt
                        areas={categories}
                        active={pointed}
                        onHover={setPointed}
                    />
                }
            >
                {/* Jump links to the areas below. */}
                <nav aria-label={t.treatments.jump}>
                    <ul className="flex flex-wrap gap-2.5">
                        {categories.map((category) => (
                            <li
                                key={category.key}
                                data-accent={category.accent}
                            >
                                <a
                                    href={`#${category.key}`}
                                    data-active={
                                        category.key === pointed
                                            ? ''
                                            : undefined
                                    }
                                    onPointerEnter={() =>
                                        setPointed(category.key)
                                    }
                                    onPointerLeave={() => setPointed(null)}
                                    onFocus={() => setPointed(category.key)}
                                    onBlur={() => setPointed(null)}
                                    className="border-line-strong inline-flex h-10 items-center gap-2.5 rounded-full border px-4 text-sm transition-colors duration-300 hover:border-accent hover:text-accent data-[active]:border-accent data-[active]:text-accent"
                                >
                                    <CategoryIcon
                                        name={category.icon}
                                        className="size-5 text-accent"
                                    />
                                    {category.name}
                                </a>
                            </li>
                        ))}
                    </ul>
                </nav>
            </PageHero>

            <div className={cx('stage-light overflow-clip', sheet)}>
                {runs(categories, groups).map(({ group, areas }) => {
                    const sections = areas.map((category) => (
                        <Fragment key={category.key}>
                            <section
                                id={category.key}
                                data-accent={category.accent}
                                aria-labelledby={`${category.key}-title`}
                                className="border-line scroll-mt-(--header-h) border-b last:border-b-0"
                            >
                                <div className="shell section-y-sm grid gap-12 lg:grid-cols-12 lg:gap-16">
                                    <div className="lg:col-span-4">
                                        <div className="lg:sticky lg:top-[calc(var(--header-h)+2.5rem)]">
                                            {/* The area's mark draws itself as the block comes into view. */}
                                            <Reveal className="flex items-center gap-5">
                                                <span className="area-badge">
                                                    <CategoryIcon
                                                        name={category.icon}
                                                        className="icon-draw text-accent-fg size-9"
                                                    />
                                                </span>
                                                <span
                                                    aria-hidden="true"
                                                    className="text-eyebrow text-soft font-semibold tabular-nums"
                                                >
                                                    {two(
                                                        order.get(
                                                            category.key,
                                                        ) ?? 0,
                                                    )}{' '}
                                                    / {two(categories.length)}
                                                </span>
                                            </Reveal>
                                            <Reveal delay={60}>
                                                <h2
                                                    id={`${category.key}-title`}
                                                    className="font-display text-display-3 mt-7"
                                                >
                                                    {category.name}
                                                </h2>
                                            </Reveal>
                                            <Reveal delay={120}>
                                                <p className="text-soft mt-5">
                                                    {category.summary}
                                                </p>
                                            </Reveal>
                                            <Reveal
                                                delay={180}
                                                className="mt-8 flex items-center gap-6"
                                            >
                                                <ButtonLink
                                                    href={category.url}
                                                    variant="outline"
                                                >
                                                    {t.common.explore}
                                                </ButtonLink>
                                                <span className="text-soft text-sm">
                                                    {t.common.treatmentCount(
                                                        category.count,
                                                    )}
                                                </span>
                                            </Reveal>
                                        </div>
                                    </div>

                                    <ul className="border-line border-t lg:col-span-8">
                                        {category.treatments.map(
                                            (treatment, index) => (
                                                <Reveal
                                                    as="li"
                                                    key={treatment.key}
                                                    delay={
                                                        Math.min(index, 6) * 40
                                                    }
                                                >
                                                    <SiteLink
                                                        href={treatment.url}
                                                        className="group border-line grid grid-cols-[1fr_auto] items-center gap-6 border-b py-6"
                                                    >
                                                        <div>
                                                            <h3 className="font-display group-hover:text-accent-fg text-2xl transition-colors duration-300 md:text-[1.75rem]">
                                                                {treatment.name}
                                                            </h3>
                                                            <p className="text-soft mt-2 line-clamp-2 max-w-2xl text-[0.9375rem]">
                                                                {
                                                                    treatment.excerpt
                                                                }
                                                            </p>
                                                        </div>
                                                        <span
                                                            aria-hidden="true"
                                                            className="border-line-strong ease-out-expo group-hover:border-accent-fg group-hover:bg-accent-fg group-hover:text-stage grid size-11 place-items-center rounded-full border transition-[background-color,color,border-color,transform] duration-500 group-hover:rotate-45"
                                                        >
                                                            <ArrowUpRight className="size-4" />
                                                        </span>
                                                    </SiteLink>
                                                </Reveal>
                                            ),
                                        )}
                                    </ul>
                                </div>
                            </section>
                        </Fragment>
                    ));

                    if (group === null) {
                        return sections;
                    }

                    // A named group: one tinted block, its heading first.
                    return (
                        <div
                            key={group.key}
                            id={group.key}
                            className="border-line bg-stage-3 scroll-mt-(--header-h) border-b last:border-b-0"
                        >
                            <div className="border-line border-b">
                                <div className="shell flex flex-wrap items-baseline justify-between gap-x-10 gap-y-2 pt-14 pb-6 md:pt-20">
                                    <p className="text-eyebrow text-accent-fg flex items-center gap-3 font-semibold uppercase">
                                        <span
                                            aria-hidden="true"
                                            className="h-px w-8 bg-current opacity-60"
                                        />
                                        <Term text={group.name} />
                                    </p>
                                    {group.tagline ? (
                                        <p className="text-soft max-w-xl">
                                            {group.tagline}
                                        </p>
                                    ) : null}
                                </div>
                            </div>
                            {sections}
                        </div>
                    );
                })}
            </div>

            <CtaBand />
        </>
    );
}
