import { useId } from 'react';
import type { CSSProperties } from 'react';
import { FaceDrawing, facePoints } from '@/site/components/art/face-map';

/**
 * The drawings of the areas showcase: one scene per main department, each
 * telling its department in its own way while the panel is held in place
 * and the page scrolls (docs/ANIMATIONS.md §8, docs/DECISIONS.md K37).
 *
 * A scene is an inline SVG whose parts read the clocks of its panel from
 * CSS variables (site.css → "Areas showcase"):
 *   --drawn  0 → 1 while the panel rises into place (the base lines draw)
 *   --beat   0 → 1 while the panel is held (the story advances)
 * and, on a part that belongs to one beat (class `st`, `--k` = its index):
 *   --u      0 → 1 across that beat
 *   --on     0 → 1 as the beat starts, and stays
 *   --now    1 only while it is the current beat
 * Without motion all of them are 1, so every scene rests in its finished
 * state. Only transforms, opacity and (for lines that draw) the dash
 * offset change; SVG parts take 2D transforms only.
 *
 * The beats are the panel's beats (DepartmentPanel.beats): a department's
 * leading treatments, or the areas of medical aesthetics. The scenes do
 * not know which ones, only how many — and, for the face, where each sits.
 *
 * The helpers and the scenes are exported: the category pages play them
 * too, beside the list of the area's treatments, together with the scenes
 * of the other areas (components/art/category-scenes.tsx, K38), and two of
 * those come back here for the groups that have no scene of their own
 * (department-scene.tsx, K46).
 */
export type SceneBeat = { zone: string | null };

export type SceneProps = { beats: SceneBeat[] };

/** Inline style of a part; the values may use the panel's clocks. */
export const css = (style: Record<string, string | number>) =>
    style as CSSProperties;

/** …and of a part that belongs to beat `k`. */
export const at = (k: number, style: Record<string, string | number> = {}) =>
    ({ '--k': k, ...style }) as CSSProperties;

/** `count` values spread evenly between `from` and `to`, half a step in from both ends. */
export const spread = (count: number, from: number, to: number) =>
    Array.from(
        { length: count },
        (_, index) => from + ((to - from) * (index + 0.5)) / count,
    );

export const list = (length: number) =>
    Array.from({ length }, (_, index) => index);

/** A soft light in the department's colour, for `fill="url(#id)"`. */
export function Glow({
    id,
    strength = 0.6,
}: {
    id: string;
    strength?: number;
}) {
    return (
        <radialGradient id={id}>
            <stop offset="0" stopColor="var(--accent)" stopOpacity={strength} />
            <stop offset="1" stopColor="var(--accent)" stopOpacity="0" />
        </radialGradient>
    );
}

/* ------------------------------------------------------------------ */
/* Hair — strand by strand, the hair comes back                        */
/* ------------------------------------------------------------------ */

/** The scalp in section: a gentle arc, y at x (0 → 1 across its width). */
const SCALP = { from: 20, to: 460, edge: 236, rise: 80 };

/** One decimal is plenty for coordinates (and keeps the server HTML short). */
const round = (value: number) => Math.round(value * 10) / 10;

const scalpAt = (t: number) => ({
    x: round(SCALP.from + (SCALP.to - SCALP.from) * t),
    y: round(SCALP.edge - SCALP.rise * t * (1 - t)),
});

const STRANDS = 17;

/**
 * The scalp in section, its follicles beneath. With the scroll the hair
 * grows back across it, from one side to the other — thin stubs become
 * full strands. Each beat sets a graft into the scalp where the growth
 * has reached and lights the follicles around it.
 */
export function HairScene({ beats }: SceneProps) {
    const glow = useId();
    const stops = spread(beats.length, 0.12, 0.88);

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <defs>
                <Glow id={glow} strength={0.5} />
            </defs>
            {/* Skin, dermis and fat */}
            <path
                pathLength={1}
                className="ln draw"
                d={`M${SCALP.from} ${SCALP.edge}Q240 ${SCALP.edge - SCALP.rise / 2} ${SCALP.to} ${SCALP.edge}`}
            />
            <path
                pathLength={1}
                className="ln draw"
                opacity="0.45"
                d="M20 304Q240 272 460 304"
            />
            <path
                pathLength={1}
                className="ln draw"
                opacity="0.25"
                d="M20 364Q240 344 460 364"
            />
            {stops.map((t, k) => {
                const { x, y } = scalpAt(t);

                return (
                    <circle
                        key={k}
                        className="st"
                        cx={x}
                        cy={y + 34}
                        r="70"
                        fill={`url(#${glow})`}
                        style={at(k, { opacity: 'calc(var(--now) * 0.9)' })}
                    />
                );
            })}
            {/* Follicles and strands: a strand grows once the front has passed it */}
            {list(STRANDS).map((index) => {
                const t = (index + 0.5) / STRANDS;
                const { x, y } = scalpAt(t);
                const length = 96 + ((index * 37) % 34);
                const lean = 22 + ((index * 13) % 16);

                return (
                    <g key={index} transform={`translate(${x} ${y})`}>
                        <path
                            className="ln"
                            d="M0 2l-9 42"
                            style={css({
                                opacity: 'calc(var(--drawn) * 0.55)',
                            })}
                        />
                        <ellipse
                            className="ln"
                            cx="-10"
                            cy="50"
                            rx="4.6"
                            ry="7"
                            transform="rotate(12 -10 50)"
                            style={css({
                                opacity: 'calc(var(--drawn) * 0.7)',
                            })}
                        />
                        <path
                            pathLength={1}
                            className="ac"
                            strokeDasharray="1"
                            d={`M0 0c-2-${round(length * 0.36)} ${round(lean * 0.3)}-${round(length * 0.72)} ${lean}-${length}`}
                            style={css({
                                '--x': Math.round(t * 1000) / 1000,
                                '--g': 'clamp(0.12, (var(--beat) * 1.3 - var(--x)) * 3 + 0.12, 1)',
                                strokeDashoffset: 'calc(1 - var(--g))',
                                opacity:
                                    'calc(var(--drawn) * (0.35 + var(--g) * 0.65))',
                            })}
                        />
                    </g>
                );
            })}
            {/* One graft per beat: it comes down and settles into the scalp */}
            {stops.map((t, k) => {
                const { x, y } = scalpAt(t);

                return (
                    <g
                        key={k}
                        className="st"
                        style={at(k)}
                        transform={`translate(${x} ${y})`}
                    >
                        <circle
                            r="30"
                            className="ac box"
                            strokeDasharray="2 6"
                            style={css({
                                opacity: 'var(--now)',
                                transform:
                                    'scale(calc(0.7 + var(--now) * 0.4))',
                            })}
                        />
                        <g
                            style={css({
                                opacity: 'var(--now)',
                                transform:
                                    'translate(0, calc((1 - clamp(0, var(--u) * 1.6, 1)) * -96px))',
                            })}
                        >
                            <path
                                className="ac"
                                d="M0 4c0-12 3-22 9-30M0 4c-1-11 1-20 5-27"
                            />
                            <ellipse
                                cx="0"
                                cy="10"
                                rx="4"
                                ry="6"
                                className="af"
                            />
                        </g>
                        <circle
                            r="4.2"
                            className="af"
                            style={css({
                                opacity: 'calc(0.3 + var(--on) * 0.7)',
                            })}
                        />
                    </g>
                );
            })}
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Medical aesthetics — the face, area by area                          */
/* ------------------------------------------------------------------ */

/**
 * The face drawing of the treatment pages. Each beat lights the place its
 * area (or treatment) is applied to — the forehead, the under-eye, the
 * cheeks, the lips… — and a fine line sweeps across the face there; a beat
 * without a single place rings the whole face.
 */
export function FaceScene({ beats }: SceneProps) {
    const glow = useId();

    return (
        <svg
            viewBox="0 22 400 334"
            className="scene"
            style={css({ overflow: 'hidden' })}
        >
            <defs>
                <Glow id={glow} />
            </defs>
            <g className="ln" style={css({ opacity: 'var(--drawn)' })}>
                <FaceDrawing />
            </g>
            {beats.map(({ zone }, k) => {
                const point = zone ? facePoints[zone] : undefined;

                return point ? (
                    <g key={k} className="st" style={at(k)}>
                        {/* The sweep: a line across the face at the place, a point travelling it */}
                        <line
                            x1="96"
                            x2="304"
                            y1={point.y}
                            y2={point.y}
                            className="ac"
                            strokeDasharray="1 7"
                            style={css({ opacity: 'calc(var(--now) * 0.8)' })}
                        />
                        <circle
                            cx="96"
                            cy={point.y}
                            r="3"
                            className="af"
                            style={css({
                                opacity: 'var(--now)',
                                transform:
                                    'translate(calc(clamp(0, var(--u), 1) * 208px), 0)',
                            })}
                        />
                        <g transform={`translate(${point.x} ${point.y})`}>
                            <circle
                                r="56"
                                fill={`url(#${glow})`}
                                style={css({ opacity: 'var(--now)' })}
                            />
                            <circle
                                r="9"
                                className="ac box"
                                style={css({
                                    opacity: 'var(--now)',
                                    transform:
                                        'scale(calc(0.6 + var(--now) * 1.1))',
                                })}
                            />
                            <circle
                                r="4.2"
                                className="af"
                                style={css({
                                    opacity: 'calc(0.3 + var(--on) * 0.7)',
                                })}
                            />
                        </g>
                    </g>
                ) : (
                    <ellipse
                        key={k}
                        pathLength={1}
                        className="st ac"
                        cx="200"
                        cy="184"
                        rx="104"
                        ry="148"
                        strokeDasharray="1"
                        style={at(k, {
                            opacity: 'var(--now)',
                            strokeDashoffset:
                                'calc(1 - clamp(0, var(--u) * 1.5, 1))',
                        })}
                    />
                );
            })}
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Men's health — a route, stop by stop                                */
/* ------------------------------------------------------------------ */

const routeStops: Record<number, [number, number][]> = {
    3: [
        [44, 336],
        [262, 213],
        [414, 92],
    ],
    4: [
        [44, 336],
        [196, 256],
        [330, 168],
        [414, 92],
    ],
};

/**
 * A route that draws itself from the first step to the last; each beat is
 * a numbered stop on it.
 */
export function MensHealthScene({ beats }: SceneProps) {
    const route =
        'M44 336c76 0 84-74 152-80 66-6 66-80 134-88 42-5 62-42 84-76';
    const stops = routeStops[beats.length] ?? routeStops[4];

    return (
        <svg viewBox="0 0 480 400" className="scene">
            {/* Ground lines the route climbs over */}
            <path
                className="ln"
                opacity="0.35"
                d="M20 372h440M60 392h360"
                style={css({ opacity: 'calc(var(--drawn) * 0.35)' })}
            />
            <path
                className="ln"
                strokeDasharray="1 9"
                d={route}
                style={css({ opacity: 'calc(var(--drawn) * 0.8)' })}
            />
            {/* It reaches each stop as that stop's beat begins. */}
            <path
                pathLength={1}
                className="ac"
                strokeWidth="2.2"
                strokeDasharray="1"
                d={route}
                style={css({
                    strokeDashoffset:
                        'calc(1 - clamp(0, var(--beat) * var(--beats) / (var(--beats) - 1), 1))',
                })}
            />
            {stops.map(([x, y], k) => (
                <g
                    key={k}
                    className="st"
                    style={at(k)}
                    transform={`translate(${x} ${y})`}
                >
                    <circle
                        r="22"
                        className="ac box"
                        style={css({
                            opacity: 'var(--now)',
                            transform: 'scale(calc(0.6 + var(--now) * 0.6))',
                        })}
                    />
                    <circle
                        r="10"
                        className="pane ln"
                        style={css({ opacity: 'var(--drawn)' })}
                    />
                    <circle
                        r="4.6"
                        className="af box"
                        style={css({ transform: 'scale(var(--on))' })}
                    />
                    <text
                        x="18"
                        y="30"
                        className="fg"
                        fontSize="14"
                        style={css({
                            opacity:
                                'calc(var(--drawn) * (0.35 + var(--now) * 0.65))',
                        })}
                    >
                        {String(k + 1).padStart(2, '0')}
                    </text>
                </g>
            ))}
            {/* The arrow of the ♂ sign, where the route ends */}
            <path
                className="st ac"
                strokeWidth="2.2"
                d="M430 76l24-24M436 50h20v20"
                style={at(stops.length - 1, { opacity: 'var(--on)' })}
            />
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Dental — the arch, tooth by tooth                                   */
/* ------------------------------------------------------------------ */

const UPPER = 12;
const LOWER = 10;

/** The arch is part of a circle far above the frame; angles in degrees, left to right. */
const ARCH = { x: 240, y: -70, radius: 300, from: 122, to: 58 };

/** Angle and place of tooth `index` of `count` on a circle of `radius`. */
function tooth(index: number, count: number, radius: number, inset = 0) {
    const from = ARCH.from - inset;
    const angle = from + (index * (ARCH.to + inset - from)) / (count - 1);
    const radians = (angle * Math.PI) / 180;

    return {
        angle,
        x: ARCH.x + radius * Math.cos(radians),
        y: ARCH.y + radius * Math.sin(radians),
    };
}

/**
 * The teeth, upper and lower. A beam sweeps along the upper arch with the
 * scroll and the teeth light up behind it; each beat rests on one part of
 * the arch.
 */
export function DentalScene({ beats }: SceneProps) {
    const rests = spread(beats.length, 0, UPPER - 1).map(Math.round);
    const point = (angle: number, radius: number) => {
        const radians = (angle * Math.PI) / 180;

        return `${(ARCH.x + radius * Math.cos(radians)).toFixed(1)} ${(ARCH.y + radius * Math.sin(radians)).toFixed(1)}`;
    };

    return (
        <svg viewBox="20 104 440 240" className="scene">
            {/* The gum line */}
            <path
                pathLength={1}
                className="ln draw"
                d={`M${point(126, 264)}A264 264 0 0 0 ${point(54, 264)}`}
            />
            {/* Lower teeth: outlines only */}
            {list(LOWER).map((index) => {
                const { angle, x, y } = tooth(index, LOWER, 358, 8);
                const middle = Math.abs(index - (LOWER - 1) / 2);
                const width = 26 - middle * 0.8;

                return (
                    <rect
                        key={index}
                        pathLength={1}
                        x={-width / 2}
                        y="-22"
                        width={width}
                        height="44"
                        rx="9"
                        className="ln draw"
                        transform={`translate(${x.toFixed(1)} ${y.toFixed(1)}) rotate(${(angle - 90).toFixed(1)})`}
                    />
                );
            })}
            {/* Upper teeth: they light up behind the beam */}
            {list(UPPER).map((index) => {
                const { angle, x, y } = tooth(index, UPPER, ARCH.radius);
                const middle = Math.abs(index - (UPPER - 1) / 2);
                const width = 30 - middle * 1.1;
                const height = 56 - middle * 2.2;

                return (
                    <rect
                        key={index}
                        x={-width / 2}
                        y={-height / 2}
                        width={width}
                        height={height}
                        rx="10"
                        className="af"
                        stroke="var(--accent)"
                        strokeWidth="1.2"
                        fillOpacity="0.32"
                        transform={`translate(${x.toFixed(1)} ${y.toFixed(1)}) rotate(${(angle - 90).toFixed(1)})`}
                        style={css({
                            '--x': index / (UPPER - 1),
                            opacity:
                                'clamp(0.2, (var(--beat) * 1.25 - var(--x)) * 6 + 0.2, 1)',
                        })}
                    />
                );
            })}
            {rests.map((index, k) => {
                const { x, y } = tooth(index, UPPER, ARCH.radius);

                return (
                    <circle
                        key={k}
                        className="st ac box"
                        cx={x}
                        cy={y}
                        r="38"
                        strokeDasharray="2 6"
                        style={at(k, {
                            opacity: 'var(--now)',
                            transform: 'scale(calc(0.7 + var(--now) * 0.4))',
                        })}
                    />
                );
            })}
            {/* The beam */}
            <g
                style={css({
                    opacity: 'var(--drawn)',
                    transformOrigin: `${ARCH.x}px ${ARCH.y}px`,
                    transform: `rotate(calc(${ARCH.from}deg - var(--beat) * ${ARCH.from - ARCH.to}deg))`,
                })}
            >
                <path
                    className="ac"
                    strokeWidth="2"
                    d={`M${ARCH.x + 232} ${ARCH.y}h104`}
                />
                <circle cx={ARCH.x + 226} cy={ARCH.y} r="4.5" className="af" />
            </g>
        </svg>
    );
}
