import { useRef } from 'react';
import type { CSSProperties, ElementType, ReactNode } from 'react';
import { useScene } from '@/site/hooks/use-scene';

type Range<T> = [from: T, to: T];

const length = (value: number | string): string =>
    typeof value === 'number' ? `${value}px` : value;

type ScrollSceneProps = {
    children: ReactNode;
    /** How many viewport heights of scrolling the scene lasts. */
    length?: number;
    /** Pin only from this breakpoint up; below it the scene is static content. */
    pinFrom?: 'lg';
    /** Called when progress changes — only for effects CSS cannot express. */
    onProgress?: (progress: number) => void;
    /** Ease the progress towards the scroll position (milliseconds, see the engine). */
    smooth?: number;
    className?: string;
    viewportClassName?: string;
    id?: string;
};

/**
 * A pinned scene: the wrapper is `length` screens tall and its viewport
 * sticks to the top while you scroll through it. Children read the scene
 * progress from the CSS variable `--p` (0 → 1) — usually through <Scrub>.
 */
export function ScrollScene({
    children,
    length: sceneLength = 3,
    pinFrom,
    onProgress,
    smooth,
    className,
    viewportClassName,
    id,
}: ScrollSceneProps) {
    const ref = useRef<HTMLDivElement>(null);

    useScene(ref, { mode: 'pin', onProgress, smooth });

    return (
        <div
            ref={ref}
            id={id}
            data-scene="pin"
            data-pin-from={pinFrom}
            className={className}
            style={{ '--scene-length': sceneLength } as CSSProperties}
        >
            <div data-scene-viewport="" className={viewportClassName}>
                {children}
            </div>
        </div>
    );
}

type ViewSceneProps = {
    children: ReactNode;
    as?: ElementType;
    /** Viewport fraction (from the top) where progress starts. Default 1. */
    start?: number;
    /** Viewport fraction (from the top) where progress ends. Default 0. */
    end?: number;
    /** Ease the progress towards the scroll position (milliseconds, see the engine). */
    smooth?: number;
    className?: string;
    style?: CSSProperties;
    'aria-hidden'?: boolean;
    /** Accent theme of the scene (see "Category accents" in site.css). */
    'data-accent'?: string;
};

/**
 * A scene driven by the element's own passage through the viewport:
 * `--p` goes 0 → 1 between the `start` and `end` lines. Use it for
 * parallax and for effects that should not pin the page.
 */
export function ViewScene({
    children,
    as: Tag = 'div',
    start,
    end,
    smooth,
    className,
    style,
    'aria-hidden': ariaHidden,
    'data-accent': accent,
}: ViewSceneProps) {
    const ref = useRef<HTMLElement>(null);

    useScene(ref, { mode: 'view', start, end, smooth });

    return (
        <Tag
            ref={ref}
            data-scene="view"
            data-accent={accent}
            aria-hidden={ariaHidden}
            className={className}
            style={style}
        >
            {children}
        </Tag>
    );
}

type ScrubProps = {
    children?: ReactNode;
    as?: ElementType;
    /** Scene progress at which the tween starts (0–1). */
    from?: number;
    /** Scene progress at which the tween ends (0–1). */
    to?: number;
    opacity?: Range<number>;
    x?: Range<number | string>;
    y?: Range<number | string>;
    scale?: Range<number>;
    className?: string;
    'aria-hidden'?: boolean;
};

/**
 * Tweens opacity / position / scale between two values while the nearest
 * scene's progress moves from `from` to `to` (eased). Pure CSS — see
 * `[data-scrub]` in site.css.
 *
 * Every variable is written explicitly so a nested <Scrub> never inherits
 * values from an outer one. Nest two to fade something in and out again.
 */
export function Scrub({
    children,
    as: Tag = 'div',
    from = 0,
    to = 1,
    opacity = [1, 1],
    x = [0, 0],
    y = [0, 0],
    scale = [1, 1],
    className,
    'aria-hidden': ariaHidden,
}: ScrubProps) {
    return (
        <Tag
            data-scrub=""
            aria-hidden={ariaHidden}
            className={className}
            style={
                {
                    '--from': from,
                    '--to': to,
                    '--o0': opacity[0],
                    '--o1': opacity[1],
                    '--x0': length(x[0]),
                    '--x1': length(x[1]),
                    '--y0': length(y[0]),
                    '--y1': length(y[1]),
                    '--s0': scale[0],
                    '--s1': scale[1],
                } as CSSProperties
            }
        >
            {children}
        </Tag>
    );
}

type ParallaxProps = {
    children: ReactNode;
    /** Total vertical travel in pixels while crossing the viewport (negative = moves up). */
    shift?: number;
    className?: string;
};

/**
 * Moves its content slightly against the scroll direction as it crosses
 * the viewport. Decorative layers only.
 */
export function Parallax({ children, shift = -80, className }: ParallaxProps) {
    return (
        <ViewScene className={className}>
            <div
                data-parallax=""
                style={{ '--shift': `${shift}px` } as CSSProperties}
            >
                {children}
            </div>
        </ViewScene>
    );
}
