import { useCallback, useEffect, useRef, useState } from 'react';
import type { CSSProperties } from 'react';
import { CategoryScene } from '@/site/components/art/category-scenes';
import { SectionHeading } from '@/site/components/ui/heading';
import { ArrowUpRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useScene } from '@/site/hooks/use-scene';
import { useT } from '@/site/i18n';
import type { TreatmentCard } from '@/site/types';

type TreatmentStoryProps = {
    /** Category key: picks the drawing (see `hasCategoryScene`). */
    category: string;
    treatments: TreatmentCard[];
};

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

/**
 * The treatments of an area next to the area's drawing. On large screens
 * the drawing stays pinned and every treatment is a tall row of the list:
 * as the rows cross the middle of the window the drawing moves on, one
 * beat per treatment — hair growing back, drops falling, an applicator
 * gliding (category-scenes.tsx) — and the row in turn stands out. On small
 * screens the drawing plays while it crosses the screen itself.
 *
 * The list is the real content (every row is a link); the drawing is
 * decoration, and both are complete without JavaScript or motion. The
 * clocks are in site.css ("Treatment story").
 */
export function TreatmentStory({ category, treatments }: TreatmentStoryProps) {
    const t = useT();
    const stage = useRef<HTMLDivElement>(null);
    const list = useRef<HTMLOListElement>(null);
    // Where the rows lie inside the list: measured when the list changes
    // size, never while scrolling.
    const rows = useRef<{ top: number; height: number }[]>([]);
    const height = useRef(0);
    const current = useRef(0);
    const [active, setActive] = useState(0);

    useEffect(() => {
        const element = list.current;

        if (!element) {
            return;
        }

        const measure = () => {
            const box = element.getBoundingClientRect();

            height.current = box.height;
            rows.current = Array.from(element.children, (row) => {
                const rect = row.getBoundingClientRect();

                return { top: rect.top - box.top, height: rect.height };
            });
        };

        const observer = new ResizeObserver(measure);

        observer.observe(element);
        measure();

        return () => observer.disconnect();
    }, []);

    // `progress`: how much of the list lies above the middle of the window.
    // The row on that line is the beat in turn; how far the line is through
    // it is how far the beat has come.
    const follow = useCallback((progress: number) => {
        const metrics = rows.current;

        if (metrics.length === 0) {
            return;
        }

        const y = progress * height.current;
        const found = metrics.findIndex((row) => y < row.top + row.height);
        const index = found === -1 ? metrics.length - 1 : found;
        const row = metrics[index];
        const within = Math.min(1, Math.max(0, (y - row.top) / row.height));

        stage.current?.style.setProperty(
            '--list',
            ((index + within) / metrics.length).toFixed(4),
        );

        if (index !== current.current) {
            current.current = index;
            setActive(index);
        }
    }, []);

    useScene(list, {
        mode: 'view',
        start: 0.5,
        end: 0.5,
        onProgress: follow,
        smooth: 80,
    });
    // The drawing's own way through the window: it draws while it comes in.
    useScene(stage, { mode: 'view', start: 1, end: 0.25 });

    return (
        <div className="grid gap-12 lg:grid-cols-12 lg:gap-16">
            <div className="lg:col-span-5">
                <div className="lg:sticky lg:top-[calc(var(--header-h)+2rem)]">
                    <SectionHeading
                        eyebrow={t.category.treatmentsEyebrow}
                        title={t.category.treatmentsTitle}
                        lead={t.category.storyLead}
                        size="display-4"
                    />
                    <div
                        ref={stage}
                        data-scene="view"
                        aria-hidden="true"
                        className="story-stage mt-10"
                        style={
                            {
                                '--beats': Math.max(1, treatments.length),
                            } as CSSProperties
                        }
                    >
                        <CategoryScene
                            category={category}
                            beats={treatments.length}
                        />
                    </div>
                    {/* Which treatment the drawing has reached (large screens, where it is pinned). */}
                    <div
                        aria-hidden="true"
                        className="mt-5 hidden items-center gap-5 lg:flex"
                    >
                        <p className="text-eyebrow text-soft font-semibold tabular-nums">
                            {two(active + 1)} / {two(treatments.length)}
                        </p>
                        <div className="bg-line h-px grow">
                            <div
                                className="bg-accent-fg ease-out-expo h-full origin-left transition-transform duration-700 rtl:origin-right"
                                style={{
                                    transform: `scaleX(${(active + 1) / treatments.length})`,
                                }}
                            />
                        </div>
                    </div>
                </div>
            </div>

            <ol ref={list} className="border-line border-t lg:col-span-7">
                {treatments.map((treatment, index) => (
                    <li
                        key={treatment.key}
                        data-active={index === active ? '' : undefined}
                        // Fixed number column: the display face has no tabular figures.
                        className="group border-line lg:motion:opacity-80 lg:motion:data-[active]:opacity-100 lg:motion:focus-within:opacity-100 lg:motion:hover:opacity-100 relative grid grid-cols-[1.75rem_1fr_auto] items-start gap-5 border-b py-7 transition-opacity duration-500 md:gap-8 lg:min-h-[44vh] lg:content-center lg:py-12"
                    >
                        <span
                            aria-hidden="true"
                            className="font-display text-accent-fg pt-1.5 text-lg tabular-nums lg:pt-2.5"
                        >
                            {two(index + 1)}
                        </span>
                        <div>
                            <h3 className="font-display lg:text-display-4 text-2xl md:text-[1.75rem]">
                                <SiteLink
                                    href={treatment.url}
                                    className="after:absolute after:inset-0"
                                >
                                    {treatment.name}
                                </SiteLink>
                            </h3>
                            <p className="text-soft mt-2 max-w-xl text-[0.9375rem] lg:mt-4 lg:text-lg">
                                {treatment.excerpt}
                            </p>
                            <span
                                aria-hidden="true"
                                className="text-accent-fg mt-5 hidden items-center gap-2 text-sm font-medium lg:inline-flex"
                            >
                                {t.common.details}
                                <ArrowUpRight className="ease-out-expo size-4 transition-transform duration-500 group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
                            </span>
                        </div>
                        <ArrowUpRight
                            aria-hidden="true"
                            className="text-soft ease-out-expo group-hover:text-accent-fg mt-2 size-5 transition-[transform,color] duration-500 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 lg:hidden"
                        />
                    </li>
                ))}
            </ol>
        </div>
    );
}
