import { useCallback, useRef, useState } from 'react';
import type { CSSProperties, FocusEvent } from 'react';
import { LineField } from '@/site/components/art/line-field';
import { ProcessArt } from '@/site/components/art/process-art';
import { MediaSlot } from '@/site/components/media/media-slot';
import { ButtonAnchor } from '@/site/components/ui/button';
import { Em } from '@/site/components/ui/em';
import { Eyebrow } from '@/site/components/ui/heading';
import { useAmbient } from '@/site/hooks/use-in-view';
import { useScene } from '@/site/hooks/use-scene';
import { useT } from '@/site/i18n';
import type { LineClock } from '@/site/lib/line-field';
import type { Media } from '@/site/types';

/**
 * The scene's timetable, in its progress (0 → 1): the heading until OPEN,
 * then the steps in equal shares until CLOSE, then the call to action.
 * A step spends the first TURN of its share arriving — the lines change
 * shape, the text comes in — and the rest being read.
 */
const OPEN = 0.1;
const CLOSE = 0.86;
const TURN = 0.42;

const clamp = (value: number) => Math.min(1, Math.max(0, value));

const two = (value: number) => String(value).padStart(2, '0');

type ProcessStoryProps = {
    /** Photo of each step, once the clinic has them (media library: home/process-1…). */
    media: (Media | null)[];
};

/**
 * The process, from the first conversation to follow-up — the scene of the
 * home page that is ours alone (docs/DECISIONS.md K40).
 *
 * While motion is on the section is pinned for a few screens and one
 * bundle of lines fills it (LineField): flowing contours at first, then,
 * step by step, two profiles facing each other, a map with a route across
 * it, rings closing on a point, orbits around a centre — and rays behind
 * the call to action. The texts ("plates") lie on top of each other and
 * take turns; a rail at the bottom shows where the visitor is.
 *
 * The texts are ordinary content: all of them are in the page from the
 * start, and without JavaScript, with reduced motion or in a very low
 * window the section is a heading, four cards with the step drawings and
 * the call — nothing is pinned or hidden. Before the canvas has drawn its
 * first frame (and in data-saver mode, where it never does) the step
 * drawings stand in for the lines.
 *
 * The scene writes each plate's clock itself and only when it changed
 * (site.css → "Process story"): scrolling never renders React, except for
 * the step label.
 */
export function ProcessStory({ media }: ProcessStoryProps) {
    const t = useT();
    const copy = t.home.process;
    const count = copy.steps.length;
    const scene = useRef<HTMLElement>(null);
    const cue = useRef<HTMLParagraphElement>(null);
    // What the lines read on every frame.
    const clock = useRef<LineClock>({ progress: 0, phase: 0 });
    const parts = useRef<{ plates: HTMLElement[]; rail: HTMLElement[] }>(null);
    const written = useRef<string[]>([]);
    const current = useRef(-1);
    // -1 the heading, 0… the steps, `count` the call to action.
    const [active, setActive] = useState(-1);

    useAmbient(cue);

    const follow = useCallback(
        (progress: number) => {
            const root = scene.current;

            if (!root) {
                return;
            }

            parts.current ??= {
                plates: Array.from(
                    root.querySelectorAll<HTMLElement>('[data-plate]'),
                ),
                rail: Array.from(
                    root.querySelectorAll<HTMLElement>('[data-rail]'),
                ),
            };

            const { plates, rail } = parts.current;
            const share = (CLOSE - OPEN) / count;
            // Plate 0 is the heading, 1…count the steps, count + 1 the call:
            // when each begins to arrive, and how long arriving takes.
            const startOf = (plate: number) =>
                plate > count ? CLOSE : OPEN + (plate - 1) * share;
            const turnOf = (plate: number) =>
                plate > count ? (1 - CLOSE) * 0.6 : share * TURN;

            // The lines: the shape in turn, and how far towards the next.
            let phase = 0;

            for (let plate = 1; plate <= count + 1; plate++) {
                if (progress >= startOf(plate)) {
                    phase =
                        plate -
                        1 +
                        clamp((progress - startOf(plate)) / turnOf(plate));
                }
            }

            clock.current.progress = progress;
            clock.current.phase = phase;

            const write = (
                slot: number,
                element: HTMLElement,
                name: string,
                value: number,
            ) => {
                const text = value.toFixed(3);

                if (written.current[slot] !== text) {
                    written.current[slot] = text;
                    element.style.setProperty(name, text);
                }
            };

            // The texts: one comes in as the lines settle, and leaves as
            // they set off again — never two at a time.
            plates.forEach((plate, index) => {
                const arrived =
                    index === 0
                        ? 1
                        : clamp(
                              (progress -
                                  startOf(index) -
                                  0.3 * turnOf(index)) /
                                  (0.7 * turnOf(index)),
                          );
                const left =
                    index > count
                        ? 0
                        : clamp(
                              (progress -
                                  startOf(index + 1) +
                                  0.15 * turnOf(index + 1)) /
                                  (0.45 * turnOf(index + 1)),
                          );
                const value = left > 0 ? left : arrived - 1;

                write(index, plate, '--c', value);
                plate.toggleAttribute('data-on', Math.abs(value) < 0.98);
            });

            rail.forEach((step, index) => {
                write(
                    plates.length + index,
                    step,
                    '--f',
                    clamp((progress - startOf(index + 1)) / share),
                );
            });

            const index =
                progress < OPEN
                    ? -1
                    : Math.min(count, Math.floor((progress - OPEN) / share));

            if (index !== current.current) {
                current.current = index;
                setActive(index);
            }
        },
        [count],
    );

    useScene(scene, { mode: 'pin', onProgress: follow, smooth: 110 });

    // The call to action can be reached with the keyboard while its plate
    // is still waiting: bring the scene to its end.
    const reach = (event: FocusEvent<HTMLAnchorElement>) => {
        const root = scene.current;
        const view = root?.firstElementChild;

        if (
            !root ||
            !view ||
            !event.target.matches(':focus-visible') ||
            getComputedStyle(view).position !== 'sticky' ||
            clock.current.progress > 0.93
        ) {
            return;
        }

        window.scrollTo({
            top:
                root.getBoundingClientRect().top +
                window.scrollY +
                (root.offsetHeight - window.innerHeight) * 0.97,
        });
    };

    return (
        <section
            ref={scene}
            id="yaklasim"
            data-scene="pin"
            className="process-story stage-dark"
        >
            <div data-scene-viewport="" className="process-view">
                <div aria-hidden="true" className="process-glow" />
                <LineField clock={clock} className="process-field" />
                {/* Keeps the text calm over the lines. */}
                <div aria-hidden="true" className="process-scrim" />

                <div className="process-body shell">
                    <div className="process-stack">
                        <header
                            data-plate=""
                            className="process-plate process-intro"
                        >
                            <div className="process-text">
                                <Eyebrow>{copy.eyebrow}</Eyebrow>
                                <h2 className="display-em font-display text-display-2">
                                    <Em text={copy.title} />
                                </h2>
                                <p className="text-lead text-soft max-w-xl">
                                    {copy.lead}
                                </p>
                                <p
                                    ref={cue}
                                    data-ambient=""
                                    aria-hidden="true"
                                    className="process-cue"
                                >
                                    <span className="process-cue-line">
                                        <span />
                                    </span>
                                    {t.common.scroll}
                                </p>
                            </div>
                        </header>

                        <ol className="process-steps">
                            {copy.steps.map((step, index) => (
                                <li
                                    key={step.title}
                                    data-plate=""
                                    className="process-plate process-step"
                                >
                                    {/*
                                     * The clinic's photo of the step, or its drawing: in
                                     * the cards of the static form, and in the pinned
                                     * scene until the lines are there.
                                     */}
                                    <div
                                        aria-hidden="true"
                                        data-photo={
                                            media[index] ? '' : undefined
                                        }
                                        className="process-visual"
                                    >
                                        <MediaSlot
                                            media={media[index]}
                                            className="size-full"
                                            sizes="(min-width: 80rem) 20rem, (min-width: 40rem) 50vw, 100vw"
                                            fallback={
                                                <ProcessArt step={index + 1} />
                                            }
                                        />
                                    </div>
                                    <div className="process-text">
                                        <p
                                            aria-hidden="true"
                                            className="process-count font-display"
                                        >
                                            {two(index + 1)}
                                        </p>
                                        <h3 className="font-display text-display-4">
                                            {step.title}
                                        </h3>
                                        <p className="process-copy text-soft">
                                            {step.text}
                                        </p>
                                        {/* What the lines are showing (pinned scene only). */}
                                        <p
                                            aria-hidden="true"
                                            className="process-motif"
                                        >
                                            {step.motif}
                                        </p>
                                    </div>
                                </li>
                            ))}
                        </ol>

                        <div
                            data-plate=""
                            className="process-plate process-outro"
                        >
                            <div className="process-text">
                                <p className="display-em font-display text-display-3">
                                    <Em text={t.cta.title} />
                                </p>
                                <p className="text-lead text-soft max-w-xl">
                                    {t.cta.text}
                                </p>
                                {/* The appointment request at the end of this page. */}
                                <ButtonAnchor
                                    href="#randevu"
                                    size="lg"
                                    onFocus={reach}
                                >
                                    {t.common.appointmentLong}
                                </ButtonAnchor>
                            </div>
                        </div>
                    </div>

                    {/* Where the visitor is in the scene (the steps themselves are above). */}
                    <div
                        aria-hidden="true"
                        className="process-hud"
                        style={{ '--steps': count } as CSSProperties}
                    >
                        <p className="process-hud-label text-eyebrow font-semibold uppercase">
                            {/* Empty under the heading: the line keeps its height. */}
                            {active < 0
                                ? ' '
                                : active >= count
                                  ? t.common.appointment
                                  : t.treatment.stepLabel(active + 1, count)}
                        </p>
                        <ol className="process-rail">
                            {copy.steps.map((step, index) => (
                                <li
                                    key={step.title}
                                    data-rail=""
                                    data-active={
                                        index === active ? '' : undefined
                                    }
                                >
                                    <span className="process-rail-bar">
                                        <span className="process-rail-fill" />
                                    </span>
                                    <span className="process-rail-name">
                                        <span className="tabular-nums">
                                            {two(index + 1)}
                                        </span>
                                        {step.title}
                                    </span>
                                </li>
                            ))}
                        </ol>
                    </div>
                </div>
            </div>
        </section>
    );
}
