import { useCallback, useRef, useState } from 'react';
import { FaceMap, hasFacePoint } from '@/site/components/art/face-map';
import { SectionHeading } from '@/site/components/ui/heading';
import { ArrowUpRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useActiveIndex } from '@/site/hooks/use-in-view';
import { useT } from '@/site/i18n';
import type { TreatmentCard } from '@/site/types';

/** A category gets the map when at least this many treatments sit on the face drawing. */
const MIN_POINTS = 3;

export function supportsZoneMap(treatments: TreatmentCard[]): boolean {
    return (
        treatments.filter((treatment) => hasFacePoint(treatment.zone)).length >=
        MIN_POINTS
    );
}

/**
 * The treatments of a category next to a face drawing: on large screens
 * the drawing stays pinned and the zone of the treatment crossing the
 * middle of the viewport lights up, so scrolling the list walks over the
 * face. Hovering a row or a hotspot highlights it as well.
 *
 * The list is the real content (every row is a link); the map is an aid.
 */
export function ZoneMap({ treatments }: { treatments: TreatmentCard[] }) {
    const t = useT();
    const listRef = useRef<HTMLOListElement>(null);
    const [scrolled, setScrolled] = useState(0);
    const [hovered, setHovered] = useState<string | null>(null);

    const getElements = useCallback(
        () => Array.from(listRef.current?.children ?? []),
        [],
    );

    useActiveIndex(getElements, setScrolled);

    const activeZone = hovered ?? treatments[scrolled]?.zone ?? null;

    return (
        <div className="grid gap-14 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.mapEyebrow}
                        title={t.category.mapTitle}
                        lead={t.category.mapLead}
                        size="display-4"
                    />
                    <FaceMap
                        className="mt-10 lg:max-h-[58svh] lg:w-auto"
                        label={t.category.mapAlt}
                        active={activeZone}
                        onHover={setHovered}
                        items={treatments
                            .filter((treatment) => treatment.zone !== null)
                            .map((treatment) => ({
                                zone: treatment.zone as string,
                                name: treatment.name,
                                url: treatment.url,
                            }))}
                    />
                </div>
            </div>

            <ol ref={listRef} className="border-line border-t lg:col-span-7">
                {treatments.map((treatment, index) => {
                    const active = hovered
                        ? treatment.zone === hovered
                        : index === scrolled;

                    return (
                        <li
                            key={treatment.key}
                            data-active={active ? '' : undefined}
                            onMouseEnter={() => setHovered(treatment.zone)}
                            onMouseLeave={() => setHovered(null)}
                            // 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 relative grid grid-cols-[1.75rem_1fr_auto] items-start gap-5 border-b py-7 transition-opacity duration-500 md:gap-8"
                        >
                            <span
                                aria-hidden="true"
                                className="font-display text-accent-fg pt-1.5 text-lg tabular-nums"
                            >
                                {String(index + 1).padStart(2, '0')}
                            </span>
                            <div>
                                <h3 className="font-display 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]">
                                    {treatment.excerpt}
                                </p>
                                {treatment.zone &&
                                !hasFacePoint(treatment.zone) ? (
                                    <p className="border-line text-soft mt-3 inline-flex rounded-full border px-3 py-1 text-xs">
                                        {t.category.mapBody}
                                    </p>
                                ) : null}
                            </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"
                            />
                        </li>
                    );
                })}
            </ol>
        </div>
    );
}
