import { useId } from 'react';
import type { ReactNode } from 'react';
import {
    at,
    css,
    DentalScene,
    Glow,
    HairScene,
    list,
    MensHealthScene,
    spread,
} from '@/site/components/sections/home/area-scenes';
import type { SceneProps } from '@/site/components/sections/home/area-scenes';

/**
 * The drawings of the category pages: one scene per area of expertise,
 * played beside the list of the area's treatments (TreatmentStory). Hair,
 * dental and men's health use the scenes of their home-page panels; the
 * six below were drawn for the areas themselves (K37/K38). Two of them are
 * also the home-page panels of their groups (K46): the orbits for
 * personalised medicine, the planning sheet for plastic surgery.
 *
 * They are written like the home page's scenes (see area-scenes.tsx): an
 * inline SVG whose parts read --drawn, --beat and, per beat (class `st`,
 * `--k`), --u, --on and --now. Here a beat is one treatment of the area.
 */

/* ------------------------------------------------------------------ */
/* Mesotherapy — drop by drop, into the skin                           */
/* ------------------------------------------------------------------ */

/**
 * The skin in section. Each beat lets one drop fall onto the surface and
 * spread beneath it.
 */
function MesotherapyScene({ beats }: SceneProps) {
    const columns = spread(beats.length, 44, 436);

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <path
                pathLength={1}
                className="ln draw"
                d="M20 184c60-22 122 22 184 0s124-22 256 4"
            />
            <path
                pathLength={1}
                className="ln draw"
                opacity="0.55"
                d="M20 262c70-18 132 20 204 2s122-18 236 4"
            />
            <path
                pathLength={1}
                className="ln draw"
                opacity="0.35"
                d="M20 338c76-16 138 18 212 2s120-16 228 4"
            />
            {/* Cells between the layers */}
            <g style={css({ opacity: 'calc(var(--drawn) * 0.3)' })}>
                {list(30).map((index) => (
                    <circle
                        key={index}
                        cx={36 + ((index * 53) % 410)}
                        cy={212 + ((index * 37) % 108)}
                        r="1.9"
                        className="fg"
                    />
                ))}
            </g>
            {columns.map((x, k) => (
                <g
                    key={k}
                    className="st"
                    style={at(k)}
                    transform={`translate(${x} 0)`}
                >
                    <line
                        className="ln"
                        y1="46"
                        y2="172"
                        strokeDasharray="1 8"
                        opacity="0.7"
                    />
                    <path
                        className="af"
                        d="M0 0c7 10 11 17 11 23a11 11 0 0 1-22 0c0-6 4-13 11-23Z"
                        style={css({
                            transform:
                                'translate(0, calc(18px + var(--on) * 128px))',
                            opacity: 'calc(0.3 + var(--on) * 0.7)',
                        })}
                    />
                    <ellipse
                        className="ac box"
                        cy="222"
                        rx="26"
                        ry="10"
                        style={css({
                            opacity: 'var(--on)',
                            transform: 'scale(calc(0.2 + var(--on) * 0.8))',
                        })}
                    />
                    <ellipse
                        className="ac box"
                        cy="226"
                        rx="50"
                        ry="20"
                        style={css({
                            opacity: 'calc(var(--now) * 0.6)',
                            transform: 'scale(calc(0.4 + var(--now) * 0.6))',
                        })}
                    />
                </g>
            ))}
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Devices — the applicator crosses the skin                           */
/* ------------------------------------------------------------------ */

/**
 * An applicator glides over the skin with the scroll; the tissue beneath
 * it lights up as it passes, and each beat marks a stop on the way.
 */
function DevicesScene({ beats }: SceneProps) {
    const columns = 15;
    const stops = spread(beats.length, 96, 384);

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <path
                pathLength={1}
                className="ln draw"
                d="M20 236c80-12 150 10 220 0s150-10 220 2"
            />
            {/* The tissue: brightest under the applicator */}
            {list(4).map((row) =>
                list(columns).map((column) => (
                    <circle
                        key={`${row}-${column}`}
                        cx={72 + column * 24}
                        cy={266 + row * 26}
                        r={3 - row * 0.4}
                        className="af"
                        style={css({
                            '--x': column / (columns - 1),
                            opacity: `clamp(0.16, ${1.25 - row * 0.16} - max(var(--x) - var(--beat), var(--beat) - var(--x)) * 4.5, 1)`,
                        })}
                    />
                )),
            )}
            {stops.map((x, k) => (
                <g
                    key={k}
                    className="st"
                    style={at(k)}
                    transform={`translate(${x} 236)`}
                >
                    <circle
                        r="13"
                        className="ac box"
                        style={css({
                            opacity: 'var(--now)',
                            transform: 'scale(calc(0.6 + var(--now) * 0.7))',
                        })}
                    />
                    <circle
                        r="3.6"
                        className="af"
                        style={css({ opacity: 'calc(0.3 + var(--on) * 0.7)' })}
                    />
                </g>
            ))}
            {/* The applicator and its waves */}
            <g
                style={css({
                    transform:
                        'translate(calc(var(--beat) * 336px - 168px), 0)',
                    opacity: 'var(--drawn)',
                })}
            >
                <path
                    className="ln"
                    d="M240 44c0-34 44-30 70-52M214 62a26 26 0 0 1 52 0v96a14 14 0 0 1-14 14h-24a14 14 0 0 1-14-14Z"
                />
                <path className="ac" d="M226 180h28M230 188h20" />
                {[18, 32, 46].map((radius) => (
                    <path
                        key={radius}
                        className="ac"
                        opacity={0.9 - radius / 70}
                        d={`M${240 - radius} 204a${radius} ${radius} 0 0 0 ${radius * 2} 0`}
                    />
                ))}
            </g>
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* IV therapy — the infusion, drop by drop                             */
/* ------------------------------------------------------------------ */

/**
 * An infusion set. While the page scrolls the level in the bag sinks and
 * the line flows; each beat is one drop in the chamber.
 */
function IvTherapyScene({ beats }: SceneProps) {
    const marks = spread(beats.length, 58, 162);

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <g className="ln">
                <path pathLength={1} className="draw" d="M240 0v24" />
                <rect
                    pathLength={1}
                    className="draw"
                    x="178"
                    y="24"
                    width="124"
                    height="152"
                    rx="26"
                />
                <path
                    pathLength={1}
                    className="draw"
                    d="M228 176h24v14h-24ZM240 190v12M226 216a14 14 0 0 1 28 0v36a14 14 0 0 1-28 0Z"
                />
            </g>
            {/* The level sinks with the scroll */}
            <rect
                x="188"
                y="46"
                width="104"
                height="120"
                rx="18"
                className="af"
                style={css({
                    opacity: 'calc(var(--drawn) * 0.26)',
                    transformBox: 'fill-box',
                    transformOrigin: '50% 100%',
                    transform: 'scaleY(calc(1 - var(--beat) * 0.6))',
                })}
            />
            {marks.map((y, k) => (
                <path
                    key={k}
                    className="st ac"
                    d={`M312 ${y}h16`}
                    style={at(k, { opacity: 'calc(0.25 + var(--now) * 0.75)' })}
                />
            ))}
            {/* One drop per beat */}
            {beats.map((_, k) => (
                <circle
                    key={k}
                    className="st af"
                    cx="240"
                    cy="212"
                    r="4.5"
                    style={at(k, {
                        opacity: 'var(--now)',
                        transform:
                            'translate(0, calc(clamp(0, var(--u), 1) * 34px))',
                    })}
                />
            ))}
            {/* The line: its dashes travel towards the patient */}
            <path
                className="ln"
                opacity="0.5"
                d="M240 266v40c0 44 44 50 84 50h136"
            />
            <path
                className="ac"
                strokeDasharray="10 14"
                d="M240 266v40c0 44 44 50 84 50h136"
                style={css({
                    opacity: 'var(--drawn)',
                    strokeDashoffset: 'calc(var(--beat) * -192)',
                })}
            />
            <rect
                x="231"
                y="282"
                width="18"
                height="14"
                rx="3"
                className="ln"
            />
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Medical longevity — orbits around a centre                          */
/* ------------------------------------------------------------------ */

const orbitTilts = [-18, 26, -42, 10];

/** Fewer beats than this leave the outer orbits empty: they are drawn faint. */
const ORBITS = 4;

/**
 * Bodies circling a centre; the scroll turns them. Each beat is one orbit;
 * with only a few beats (a home-page group of two areas) the outer orbits
 * are drawn faintly, without a beat of their own.
 */
export function LongevityScene({ beats }: SceneProps) {
    const glow = useId();
    const orbits = Math.max(ORBITS, beats.length);
    // The orbits share the room between the centre and the edge.
    const step = Math.min(36, 150 / Math.max(1, orbits - 1));

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <defs>
                <Glow id={glow} strength={0.5} />
            </defs>
            <circle
                cx="240"
                cy="200"
                r="96"
                fill={`url(#${glow})`}
                style={css({ opacity: 'var(--drawn)' })}
            />
            {beats.map((_, k) => {
                const radius = 78 + k * step;

                return (
                    <g
                        key={k}
                        className="st"
                        style={at(k)}
                        transform={`translate(240 200) rotate(${orbitTilts[k % orbitTilts.length]}) scale(1 0.42)`}
                    >
                        <circle
                            r={radius}
                            className="ac"
                            vectorEffect="non-scaling-stroke"
                            style={css({
                                opacity: 'calc(0.22 + var(--now) * 0.78)',
                            })}
                        />
                        <g
                            style={css({
                                transform: `rotate(calc(var(--beat) * ${(k % 2 ? -1 : 1) * (250 + k * 60)}deg + ${k * 97}deg))`,
                            })}
                        >
                            <circle
                                cx={radius}
                                r="9"
                                className="af"
                                style={css({
                                    opacity: 'calc(0.4 + var(--on) * 0.6)',
                                })}
                            />
                        </g>
                    </g>
                );
            })}
            {list(orbits - beats.length).map((index) => {
                const k = beats.length + index;
                const radius = 78 + k * step;

                return (
                    <g
                        key={k}
                        transform={`translate(240 200) rotate(${orbitTilts[k % orbitTilts.length]}) scale(1 0.42)`}
                        style={css({ opacity: 'calc(var(--drawn) * 0.35)' })}
                    >
                        <circle
                            r={radius}
                            className="ln"
                            vectorEffect="non-scaling-stroke"
                        />
                        <g
                            style={css({
                                transform: `rotate(calc(var(--beat) * ${(k % 2 ? -1 : 1) * 180}deg + ${k * 97}deg))`,
                            })}
                        >
                            <circle cx={radius} r="6" className="af" />
                        </g>
                    </g>
                );
            })}
            {/* The centre: ∞ */}
            <g style={css({ opacity: 'var(--drawn)' })}>
                <circle cx="240" cy="200" r="34" className="pane ln" />
                <path
                    className="ac"
                    strokeWidth="1.2"
                    transform="translate(206.4 166.4) scale(1.4)"
                    d="M24 24c-4-8-16-8-16 0s12 8 16 0c4-8 16-8 16 0s-12 8-16 0Z"
                />
            </g>
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Plastic surgery — the plan, measure by measure                      */
/* ------------------------------------------------------------------ */

/** The measures of the plan: y, and the two ends on the outline. */
const measures: [number, number, number][] = [
    [128, 108, 372],
    [236, 146, 334],
    [332, 116, 364],
];

/**
 * A planning sheet: an outline drawn on a dotted grid. Each beat takes one
 * measure; the last draws the axis — and the planned line settles inside
 * the outline as the page scrolls.
 */
export function PlasticSurgeryScene({ beats }: SceneProps) {
    const grid = useId();
    const outline =
        'M205 22c0 22-16 30-56 32-40 6-52 46-38 88 12 38 40 56 35 98-4 38-34 64-28 138M275 22c0 22 16 30 56 32 40 6 52 46 38 88-12 38-40 56-35 98 4 38 34 64 28 138';

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <defs>
                <pattern
                    id={grid}
                    width="24"
                    height="24"
                    patternUnits="userSpaceOnUse"
                >
                    <circle cx="12" cy="12" r="1" className="fg" />
                </pattern>
            </defs>
            <rect
                width="480"
                height="400"
                fill={`url(#${grid})`}
                style={css({ opacity: 'calc(var(--drawn) * 0.22)' })}
            />
            <path pathLength={1} className="ln draw" d={outline} />
            {/* The planned line, a little inside the outline */}
            <path
                className="ac"
                strokeDasharray="3 7"
                d={outline}
                style={css({
                    transformOrigin: '240px 200px',
                    transform: 'scale(calc(1 - var(--beat) * 0.07), 1)',
                    opacity: 'calc(var(--beat) * 0.9)',
                })}
            />
            {beats.map((_, k) => {
                const measure = measures[k];

                return measure ? (
                    <g key={k} className="st" style={at(k)}>
                        <path
                            className="ac box"
                            d={`M${measure[1]} ${measure[0]}H${measure[2]}`}
                            style={css({ transform: 'scaleX(var(--on))' })}
                        />
                        <path
                            className="ac"
                            d={`M${measure[1]} ${measure[0] - 9}v18M${measure[2]} ${measure[0] - 9}v18`}
                            style={css({ opacity: 'var(--on)' })}
                        />
                        <rect
                            x="233"
                            y={measure[0] - 7}
                            width="14"
                            height="14"
                            className="af box"
                            style={css({
                                opacity: 'var(--now)',
                                transform: 'rotate(45deg) scale(var(--now))',
                            })}
                        />
                    </g>
                ) : (
                    <path
                        key={k}
                        className="st ac box"
                        strokeDasharray="8 8"
                        d="M240 30v350"
                        style={at(k, { transform: 'scaleY(var(--on))' })}
                    />
                );
            })}
        </svg>
    );
}

/* ------------------------------------------------------------------ */
/* Beauty — a bloom                                                    */
/* ------------------------------------------------------------------ */

const PETALS = 10;

const sparkles: [number, number, number][] = [
    [96, 84, 1],
    [392, 112, 0.8],
    [408, 304, 1.1],
    [84, 296, 0.7],
];

/**
 * Petals folded over one another open into a rosette as the page scrolls;
 * each beat sets one sparkle.
 */
function BeautyScene({ beats }: SceneProps) {
    const glow = useId();

    return (
        <svg viewBox="0 0 480 400" className="scene">
            <defs>
                <Glow id={glow} strength={0.45} />
            </defs>
            <circle
                cx="240"
                cy="200"
                r="150"
                fill={`url(#${glow})`}
                style={css({ opacity: 'var(--drawn)' })}
            />
            <circle
                cx="240"
                cy="200"
                r="162"
                className="ln"
                strokeDasharray="1 10"
                style={css({
                    opacity: 'var(--drawn)',
                    transformOrigin: '240px 200px',
                    transform: 'rotate(calc(var(--beat) * 60deg))',
                })}
            />
            {list(PETALS).map((index) => (
                <ellipse
                    key={index}
                    cx="240"
                    cy="126"
                    rx="24"
                    ry="74"
                    className="ac"
                    fill="var(--accent)"
                    fillOpacity="0.07"
                    style={css({
                        opacity: 'var(--drawn)',
                        transformOrigin: '240px 200px',
                        transform: `rotate(calc(${((index - (PETALS - 1) / 2) * 360) / PETALS}deg * (0.1 + var(--beat) * 0.9)))`,
                    })}
                />
            ))}
            <circle cx="240" cy="200" r="13" className="pane ac" />
            <circle cx="240" cy="200" r="4" className="af" />
            {beats.map((_, k) => {
                const [x, y, size] = sparkles[k % sparkles.length];

                return (
                    <g
                        key={k}
                        className="st"
                        style={at(k)}
                        transform={`translate(${x} ${y}) scale(${size})`}
                    >
                        <path
                            className="af box"
                            d="M0-22c2 14 8 20 22 22-14 2-20 8-22 22-2-14-8-20-22-22 14-2 20-8 22-22Z"
                            style={css({
                                opacity: 'calc(0.2 + var(--on) * 0.8)',
                                transform:
                                    'scale(calc(0.3 + var(--on) * 0.7)) rotate(calc(var(--now) * 45deg))',
                            })}
                        />
                    </g>
                );
            })}
        </svg>
    );
}

/** Scenes by category key. Botox and fillers show the face map instead (ZoneMap). */
const scenes: Partial<Record<string, (props: SceneProps) => ReactNode>> = {
    hair: HairScene,
    dental: DentalScene,
    mesotherapy: MesotherapyScene,
    devices: DevicesScene,
    beauty: BeautyScene,
    'mens-health': MensHealthScene,
    'iv-therapy': IvTherapyScene,
    longevity: LongevityScene,
    'plastic-surgery': PlasticSurgeryScene,
};

export function hasCategoryScene(category: string): boolean {
    return category in scenes;
}

type CategorySceneProps = {
    /** Category key: picks the scene. */
    category: string;
    /** Number of beats: the treatments of the area. */
    beats: number;
};

/** The drawing of one area; decorative (the list beside it carries the text). */
export function CategoryScene({ category, beats }: CategorySceneProps) {
    const Scene = scenes[category];

    return Scene ? (
        <Scene beats={Array.from({ length: beats }, () => ({ zone: null }))} />
    ) : null;
}
