import { useCallback, useRef, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { useActiveIndex } from '@/site/hooks/use-in-view';
import { useScene } from '@/site/hooks/use-scene';
import { cx } from '@/site/lib/cx';

type Step = { title: string; text: string };

type StickyStepsProps = {
    steps: Step[];
    /** Content pinned beside the steps (usually the section heading). */
    aside: ReactNode;
    /** Label of the current step, e.g. "Adım 2 / 4". */
    stepLabel: (index: number, total: number) => string;
    /**
     * One picture per step. On large screens they share a frame under the
     * heading and change as the steps scroll past; on small screens each
     * step shows its own.
     */
    visuals?: ReactNode[];
    className?: string;
};

const number = (index: number) => String(index + 1).padStart(2, '0');

/**
 * A step-by-step story: on large screens the aside (heading, picture or big
 * step number, progress line) stays pinned while the steps scroll past, and
 * the step crossing the middle of the viewport is highlighted.
 *
 * On small screens, without JavaScript or with reduced motion it is an
 * ordinary ordered list — nothing is hidden.
 */
export function StickySteps({
    steps,
    aside,
    stepLabel,
    visuals,
    className,
}: StickyStepsProps) {
    const listRef = useRef<HTMLOListElement>(null);
    const [active, setActive] = useState(0);

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

    useActiveIndex(getElements, setActive);
    // How much of the list lies above the middle of the window: the line beside it.
    useScene(listRef, { mode: 'view', start: 0.5, end: 0.5 });

    const progress = (
        <div className="flex grow flex-col gap-3">
            <p className="text-eyebrow text-soft font-semibold uppercase">
                {stepLabel(active + 1, steps.length)}
            </p>
            <div className="bg-line h-px w-full">
                <div
                    className="bg-accent-fg ease-out-expo h-full origin-left transition-transform duration-700 rtl:origin-right"
                    style={
                        {
                            transform: `scaleX(${(active + 1) / steps.length})`,
                        } as CSSProperties
                    }
                />
            </div>
        </div>
    );

    // The running number: the old one leaves upwards, the new one rises in.
    const counter = (size: string) => (
        <div
            className={cx(
                'font-display relative h-[1em] w-[1.25em] overflow-hidden leading-none',
                size,
            )}
        >
            {steps.map((step, index) => (
                <span
                    key={step.title}
                    className={cx(
                        'ease-out-expo absolute inset-0 transition-[transform,opacity] duration-700',
                        index === active
                            ? 'translate-y-0 opacity-100'
                            : index < active
                              ? '-translate-y-full opacity-0'
                              : 'translate-y-full opacity-0',
                    )}
                >
                    {number(index)}
                </span>
            ))}
        </div>
    );

    return (
        <div className={cx('grid gap-12 lg:grid-cols-12 lg:gap-16', className)}>
            <div className="lg:col-span-5">
                <div className="lg:sticky lg:top-[calc(var(--header-h)+2.5rem)]">
                    {aside}

                    {/* Decorative, large screens only: the list itself carries the content. */}
                    {visuals ? (
                        <div
                            aria-hidden="true"
                            className="mt-10 hidden lg:block"
                        >
                            <div className="border-line relative isolate aspect-[16/10] max-h-[40svh] w-full overflow-hidden rounded-xl border">
                                {visuals.map((visual, index) => (
                                    <div
                                        key={index}
                                        className={cx(
                                            'ease-out-expo absolute inset-0 transition-[transform,opacity] duration-[900ms]',
                                            index === active
                                                ? 'scale-100 opacity-100'
                                                : 'scale-110 opacity-0',
                                        )}
                                    >
                                        {visual}
                                    </div>
                                ))}
                                {/* Keeps the number readable over any photo. */}
                                <div className="from-ink/70 absolute inset-x-0 bottom-0 h-1/2 bg-linear-to-t to-transparent" />
                                <div className="stage-dark text-accent-fg absolute start-5 bottom-4 bg-transparent">
                                    {counter('text-7xl')}
                                </div>
                            </div>
                            <div className="mt-6">{progress}</div>
                        </div>
                    ) : (
                        // A dial: its ring closes step by step around the running number.
                        <div
                            aria-hidden="true"
                            className="mt-12 hidden items-center gap-8 lg:flex"
                        >
                            <div className="relative size-44 shrink-0">
                                <svg
                                    viewBox="0 0 120 120"
                                    className="art size-full -rotate-90"
                                >
                                    <circle
                                        cx="60"
                                        cy="60"
                                        r="54"
                                        className="ln"
                                        opacity="0.45"
                                    />
                                    {steps.map((step, index) => (
                                        <path
                                            key={step.title}
                                            className="ln"
                                            d="M106 60h7"
                                            transform={`rotate(${((index + 1) / steps.length) * 360} 60 60)`}
                                        />
                                    ))}
                                    <circle
                                        pathLength={1}
                                        cx="60"
                                        cy="60"
                                        r="54"
                                        className="ac steps-dial"
                                        strokeWidth="2.4"
                                        strokeDasharray="1"
                                        style={{
                                            strokeDashoffset:
                                                1 - (active + 1) / steps.length,
                                        }}
                                    />
                                </svg>
                                <div className="text-accent-fg absolute inset-0 grid place-items-center">
                                    {counter('text-7xl')}
                                </div>
                            </div>
                            <div className="flex grow">{progress}</div>
                        </div>
                    )}
                </div>
            </div>

            {/* A line runs down beside the steps and fills as they pass (`.steps-list` in site.css). */}
            <ol
                ref={listRef}
                data-scene="view"
                className="steps-list lg:col-span-7"
            >
                {steps.map((step, index) => (
                    <li
                        key={step.title}
                        data-active={index === active ? '' : undefined}
                        // Steps waiting their turn step back, but stay readable: at
                        // 80 % the soft text and every accent keep 4.5:1 on the
                        // ink ground (the same value in TreatmentStory and ZoneMap).
                        className="border-line lg:motion:opacity-80 lg:motion:data-[active]:opacity-100 flex flex-col justify-center border-t py-10 transition-opacity duration-700 first:border-t-0 first:pt-0 lg:min-h-[58vh] lg:py-16"
                    >
                        {visuals?.[index] ? (
                            <div
                                aria-hidden="true"
                                className="border-line mb-7 aspect-[16/9] overflow-hidden rounded-lg border lg:hidden"
                            >
                                {visuals[index]}
                            </div>
                        ) : null}
                        <p className="font-display text-accent-fg mb-5 text-2xl lg:hidden">
                            {number(index)}
                        </p>
                        <h3 className="font-display text-display-4">
                            {step.title}
                        </h3>
                        <p className="text-soft mt-5 max-w-xl text-lg">
                            {step.text}
                        </p>
                    </li>
                ))}
            </ol>
        </div>
    );
}
