import { useCallback, useRef } from 'react';
import type { CSSProperties, FocusEvent } from 'react';
import { Reveal } from '@/site/components/motion/reveal';
import { AreaScene } from '@/site/components/sections/home/department-scene';
import { ButtonLink } from '@/site/components/ui/button';
import { SectionHeading } from '@/site/components/ui/heading';
import { ArrowDown, ArrowRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useScene } from '@/site/hooks/use-scene';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { DepartmentPanel } from '@/site/types';

/**
 * The line the panels stick to, as a fraction of the viewport height. The
 * deck's progress is measured at the same line (`.areas-deck > li { top }`
 * in site.css is 10svh): change the two together.
 */
const STICK = 0.1;

const order = (index: number) => ({ '--j': index }) as CSSProperties;

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

type AreasShowcaseProps = {
    /** The six service groups, in their order: each gets a panel and a scene. */
    departments: DepartmentPanel[];
};

/**
 * The service groups (docs/DECISIONS.md K46): personalised medicine, oral
 * and dental health, hair, medical aesthetics, men's health and plastic
 * surgery — in that order, the same as the menus. The heading states the
 * approach in the clinic's own words and counts nothing. Then the groups,
 * one after another: every one gets a panel of the same size with the same
 * parts — its name and promise, its beats (a few treatments, or for a group
 * of several areas its areas) and a drawing of its own.
 *
 * While motion is on the panels stack: each one sticks below the header,
 * is held there while the page scrolls on, and then the next slides over
 * it. While a panel is held its drawing tells the department in its own
 * way — hair growing back strand by strand, an arch scanned tooth by
 * tooth, a face lit area by area, a route stop by stop (area-scenes.tsx)
 * — and the beats beside it take turns: the one in turn is highlighted
 * and its description shown.
 *
 * All of it follows one scroll scene laid over the deck; the arithmetic
 * is in site.css ("Areas showcase"). Without JavaScript, with reduced
 * motion and in very low windows the panels are a plain column of cards
 * with finished drawings.
 *
 * It is the light sheet that slides over the hero.
 */
export function AreasShowcase({ departments }: AreasShowcaseProps) {
    const { nav } = useShared();
    const t = useT();
    const probe = useRef<HTMLDivElement>(null);
    const deck = useRef<HTMLOListElement>(null);
    const clocks = useRef<string[]>([]);

    // The scene is an empty box laid over the deck: its progress is handed
    // on to the panels here, as each panel's own clock (--q, see site.css),
    // and only to those whose clock moved. Writing one variable on the deck
    // would have the browser restyle every panel on every frame; this way
    // it restyles the one or two that are in motion.
    const distribute = useCallback((progress: number) => {
        const panels = deck.current?.children;

        if (!panels) {
            return;
        }

        for (let index = 0; index < panels.length; index++) {
            const clock = Math.max(
                -1,
                Math.min(1, progress * panels.length - index),
            ).toFixed(4);

            if (clocks.current[index] !== clock) {
                clocks.current[index] = clock;
                (panels[index] as HTMLElement).style.setProperty('--q', clock);
            }
        }
    }, []);

    useScene(probe, {
        mode: 'view',
        start: STICK,
        end: STICK,
        onProgress: distribute,
    });

    // A panel that is covered by a later one holds links too: when the
    // keyboard reaches one, bring its panel to the front.
    const reveal = (event: FocusEvent<HTMLOListElement>) => {
        const panel = event.target.closest<HTMLElement>('[data-area]');

        if (!panel || !event.target.matches(':focus-visible')) {
            return;
        }

        const style = getComputedStyle(panel);

        if (style.position !== 'sticky') {
            return;
        }

        // The deck is exactly one step per panel tall (see site.css).
        const step =
            event.currentTarget.offsetHeight /
            event.currentTarget.children.length;
        const top =
            event.currentTarget.getBoundingClientRect().top +
            window.scrollY +
            Number(panel.dataset.area) * step -
            parseFloat(style.top);

        // Anywhere in the panel's own hold is fine; elsewhere, go to its start.
        if (window.scrollY < top - 8 || window.scrollY > top + step * 0.5) {
            window.scrollTo({ top });
        }
    };

    return (
        <section
            id="areas"
            className="stage-light section-y relative z-10 -mt-10 scroll-mt-(--header-h) rounded-t-xl"
        >
            <div className="shell">
                <div className="flex flex-wrap items-end justify-between gap-8">
                    <SectionHeading
                        eyebrow={t.home.areas.eyebrow}
                        title={t.home.areas.title}
                        lead={t.home.areas.lead}
                    />
                    <Reveal>
                        <ButtonLink
                            href={nav.pages.treatments.url}
                            variant="outline"
                        >
                            {t.common.viewAll}
                        </ButtonLink>
                    </Reveal>
                </div>

                {departments.length > 0 ? (
                    // The panels make a long stretch: a way past them.
                    <Reveal delay={120} className="mt-8">
                        <a
                            href="#areas-end"
                            className="text-soft hover:text-fg inline-flex items-center gap-2 text-sm underline underline-offset-4 transition-colors"
                        >
                            {t.home.areas.skip}
                            <ArrowDown className="size-4" />
                        </a>
                    </Reveal>
                ) : null}
            </div>

            {departments.length > 0 ? (
                <>
                    <div className="relative mt-12 md:mt-16">
                        <div
                            ref={probe}
                            aria-hidden="true"
                            className="pointer-events-none absolute inset-0"
                        />
                        <ol
                            ref={deck}
                            onFocus={reveal}
                            className="areas-deck shell"
                        >
                            {departments.map((department, index) => (
                                <li
                                    key={department.key}
                                    data-area={index}
                                    data-accent={department.accent}
                                    style={
                                        {
                                            '--i': index,
                                            '--beats': Math.max(
                                                1,
                                                department.beats.length,
                                            ),
                                        } as CSSProperties
                                    }
                                >
                                    <DepartmentPanelView
                                        department={department}
                                        index={index}
                                        total={departments.length}
                                    />
                                </li>
                            ))}
                        </ol>
                    </div>
                </>
            ) : null}

            <div id="areas-end" className="scroll-mt-(--header-h)" />
        </section>
    );
}

type DepartmentPanelViewProps = {
    department: DepartmentPanel;
    index: number;
    total: number;
};

/**
 * One department: its text on one side, its drawing on the other (they
 * change sides from panel to panel on wide screens; on phones the drawing
 * is on top and takes the room the text leaves). The beats listed are the
 * beats of the drawing; under them, the description of the one in turn.
 */
function DepartmentPanelView({
    department,
    index,
    total,
}: DepartmentPanelViewProps) {
    const t = useT();
    // A department of several areas lists its areas, one of one area its treatments.
    const { grouped } = department;

    return (
        <article className="area-panel stage-dark border-line relative isolate flex flex-col overflow-hidden rounded-xl border lg:grid lg:grid-cols-12">
            <div aria-hidden="true" className="area-glow" />
            <p
                aria-hidden="true"
                lang={department.lang ?? undefined}
                className="area-ghost font-display"
            >
                {department.label}
            </p>

            <div className="relative flex flex-col px-5 pt-3 pb-5 md:px-10 md:pb-9 lg:col-span-5 lg:p-10 xl:p-12">
                <div
                    className="area-in flex items-center justify-between gap-4"
                    style={order(0)}
                >
                    <p className="text-eyebrow text-accent-fg flex items-center gap-3 font-semibold whitespace-nowrap uppercase">
                        <span className="tabular-nums">
                            {two(index + 1)} / {two(total)}
                        </span>
                        <span
                            aria-hidden="true"
                            className="hidden h-px w-8 bg-current opacity-60 sm:block"
                        />
                        {grouped
                            ? t.home.areas.areaCount(department.beats.length)
                            : t.common.treatmentCount(department.count)}
                    </p>
                    {/* The way to the department's page (or its group of areas). */}
                    <SiteLink
                        href={department.url}
                        className="text-accent-fg hover:text-fg inline-flex items-center gap-1.5 text-sm font-medium whitespace-nowrap transition-colors duration-300"
                    >
                        {t.common.explore}
                        <span className="sr-only">: {department.name}</span>
                        <ArrowRight className="size-4 rtl:-scale-x-100" />
                    </SiteLink>
                </div>

                <h3
                    className="area-in font-display text-display-3 mt-3 lg:mt-auto lg:pt-6"
                    style={order(1)}
                >
                    <SiteLink
                        href={department.url}
                        lang={department.lang ?? undefined}
                        className="hover:text-accent-fg transition-colors duration-300"
                    >
                        {department.name}
                    </SiteLink>
                </h3>
                <p
                    className="area-in area-tagline text-soft mt-3 hidden max-w-md md:block lg:text-[1.0625rem]"
                    style={order(2)}
                >
                    {department.tagline}
                </p>

                {department.beats.length > 0 ? (
                    <ol
                        aria-label={
                            grouped
                                ? t.home.areas.areas(department.name)
                                : t.home.areas.treatments(department.name)
                        }
                        className="area-in mt-3.5 flex flex-col md:mt-5 lg:mt-6"
                        style={order(3)}
                    >
                        {department.beats.map((beat, k) => (
                            <li
                                key={beat.key}
                                className="st area-beat flex items-center gap-3 py-1.5 text-sm md:text-[0.9375rem] lg:py-2"
                                style={{ '--k': k } as CSSProperties}
                            >
                                <span
                                    aria-hidden="true"
                                    className="area-beat-mark"
                                />
                                <SiteLink
                                    href={beat.url}
                                    lang={beat.lang ?? undefined}
                                    className="hover:text-accent-fg font-medium transition-colors duration-300"
                                >
                                    {beat.name}
                                </SiteLink>
                            </li>
                        ))}
                    </ol>
                ) : null}

                {/* What the beat in turn is, in a sentence or two (shown while the scene plays). */}
                <div className="area-in area-captions" style={order(4)}>
                    {department.beats.map((beat, k) => (
                        <p
                            key={beat.key}
                            className="st area-caption text-soft line-clamp-3 text-sm md:text-[0.9375rem]"
                            style={{ '--k': k } as CSSProperties}
                        >
                            {beat.excerpt}
                        </p>
                    ))}
                </div>
            </div>

            <div
                aria-hidden="true"
                className={cx(
                    'area-stage order-first lg:col-span-7',
                    index % 2 === 0 ? 'lg:order-last' : 'lg:order-first',
                )}
            >
                <AreaScene
                    area={department.key}
                    icon={department.icon}
                    beats={department.beats.map(({ zone }) => ({ zone }))}
                />
            </div>
        </article>
    );
}
