(() => {
    const duration = 29.022031;
    const stage = document.getElementById('stage');
    const stage_wrap = document.getElementById('stage_wrap');
    const timeline = document.getElementById('timeline');
    const play_button = document.getElementById('play_button');
    const mute_button = document.getElementById('mute_button');
    const soundtrack = document.getElementById('soundtrack');
    const time_current = document.getElementById('time_current');
    const scene_label = document.getElementById('scene_label');
    const global_progress = document.getElementById('global_progress');
    const global_cursor = document.getElementById('global_cursor');
    const cursor_label = document.getElementById('cursor_label');
    const global_flash = document.getElementById('global_flash');

    const scene_config = [
        {id: 'scene_signal', label: 'Signal', start: 0, end: 1.6},
        {id: 'scene_selector', label: 'Selector to prompt', start: 1.6, end: 4.8},
        {id: 'scene_process', label: 'Process montage', start: 4.8, end: 8},
        {id: 'scene_orchestration', label: 'Operational orchestration', start: 8, end: 11.2},
        {id: 'scene_network', label: 'Generative network', start: 11.2, end: 14.4},
        {id: 'scene_workspace', label: 'Live workspace', start: 14.4, end: 17.6},
        {id: 'scene_interface', label: 'Interface theatre', start: 17.6, end: 20.8},
        {id: 'scene_depth', label: 'Depth field', start: 20.8, end: 24},
        {id: 'scene_clarity', label: 'From chaos to clarity', start: 24, end: 27.2},
        {id: 'scene_invitation', label: 'Invitation', start: 27.2, end: duration},
    ].map(scene => ({
        ...scene,
        element: document.getElementById(scene.id),
    }));

    let current_time = 0;
    let playing = false;
    let play_started_at = 0;
    let play_started_time = 0;
    let animation_frame = 0;

    const clamp = value => Math.max(0, Math.min(1, value));
    const range = (value, start, end) => clamp((value - start) / (end - start));
    const lerp = (start, end, progress) => start + ((end - start) * progress);
    const ease_out = value => 1 - Math.pow(1 - clamp(value), 3);
    const ease_in = value => Math.pow(clamp(value), 3);
    const ease_in_out = value => {
        const progress = clamp(value);
        return progress < 0.5
            ? 4 * progress * progress * progress
            : 1 - Math.pow(-2 * progress + 2, 3) / 2;
    };
    const ease_back = value => {
        const progress = clamp(value);
        const c1 = 1.70158;
        const c3 = c1 + 1;
        return 1 + c3 * Math.pow(progress - 1, 3) + c1 * Math.pow(progress - 1, 2);
    };
    const ease_elastic = value => {
        const progress = clamp(value);
        if (progress === 0 || progress === 1) {
            return progress;
        }
        return Math.pow(2, -10 * progress) * Math.sin((progress * 10 - 0.75) * (2 * Math.PI / 3)) + 1;
    };
    const segment_visibility = (progress, start, end, feather = 0.08) => {
        const enter = ease_out(range(progress, start, Math.min(end, start + feather)));
        const leave = 1 - ease_in(range(progress, Math.max(start, end - feather), end));
        return Math.min(enter, leave);
    };
    const set_transform = (element, transform) => {
        element.style.transform = transform;
    };
    const set_opacity = (element, value) => {
        element.style.opacity = String(clamp(value));
    };
    const type_text = (element, html, progress) => {
        const plain_length = html.replace(/<[^>]*>/g, '').length;
        const visible = Math.round(plain_length * clamp(progress));
        let count = 0;
        let output = '';
        let in_tag = false;
        let tag = '';

        for (const character of html) {
            if (character === '<') {
                in_tag = true;
                tag = character;
                continue;
            }
            if (in_tag) {
                tag += character;
                if (character === '>') {
                    output += tag;
                    tag = '';
                    in_tag = false;
                }
                continue;
            }
            if (count >= visible) {
                break;
            }
            output += character;
            count += 1;
        }

        const open_tags = [...output.matchAll(/<(strong|em|span)[^>]*>/g)].map(match => match[1]);
        const closed_tags = [...output.matchAll(/<\/(strong|em|span)>/g)].map(match => match[1]);
        open_tags.slice(closed_tags.length).reverse().forEach(tag_name => {
            output += `</${tag_name}>`;
        });
        element.innerHTML = output;
    };

    const network_labels = [
        ['8', 'ACTIVE AGENTS'],
        ['24', 'LIVE TASKS'],
        ['384', 'SOURCES'],
        ['14', 'EVAL SUITES'],
        ['28', 'OUTPUTS'],
        ['6', 'TOOLS'],
        ['3', 'WORKSPACES'],
        ['12', 'FINDINGS'],
        ['96', 'CITATIONS'],
        ['7', 'MODELS'],
        ['4', 'HANDOFFS'],
        ['1', 'MISSION'],
    ];
    const network_nodes = document.getElementById('network_nodes');
    network_labels.forEach(([value, label], index) => {
        const node = document.createElement('div');
        node.className = 'network-node';
        node.dataset.networkNode = String(index);
        node.innerHTML = `<strong>${value}</strong><span>${label}</span>`;
        network_nodes.appendChild(node);
    });

    const token_positions = [
        [1045, 74, 0.92, -15, 0.3],
        [1150, 300, 0.7, 22, 0.6],
        [875, 512, 1.12, -32, 0.15],
        [695, 83, 0.56, 38, 1.1],
        [765, 370, 0.82, 12, 0.8],
        [1220, 560, 1.28, -20, 0.05],
        [548, 590, 0.64, 28, 1.25],
        [990, 240, 0.48, -42, 1.4],
    ];
    const token_field = document.getElementById('token_field');
    token_positions.forEach((position, index) => {
        const token = document.createElement('div');
        token.className = 'token';
        token.dataset.token = String(index);
        token.textContent = '✦';
        token_field.appendChild(token);
    });

    const fit_stage = () => {
        if (document.body.classList.contains('render-mode')) {
            stage.style.transform = 'none';
            return;
        }
        const scale = stage_wrap.clientWidth / 1280;
        stage.style.transform = `scale(${scale})`;
    };

    const render_scene_visibility = time => {
        let active_scene = scene_config[0];
        scene_config.forEach((scene, index) => {
            const transition = index === scene_config.length - 1 ? 0.1 : 0.13;
            const enter = scene.start === 0 ? 1 : ease_out(range(time, scene.start - transition, scene.start + transition));
            const leave = scene.end === duration ? 1 : 1 - ease_in(range(time, scene.end - transition, scene.end + transition));
            const opacity = Math.min(enter, leave);
            scene.element.style.opacity = String(opacity);
            scene.element.style.visibility = opacity > 0.001 ? 'visible' : 'hidden';
            if (time >= scene.start) {
                active_scene = scene;
            }
        });
        return active_scene;
    };

    const render_signal = time => {
        const local = range(time, 0, 1.6);
        const arrive = ease_out(range(local, 0, 0.38));
        const lockup = document.querySelector('.signal-lockup');
        set_opacity(lockup, arrive);
        set_transform(lockup, `translateY(${lerp(38, 0, arrive)}px) scale(${lerp(0.95, 1, arrive)})`);

        document.querySelectorAll('.signal-copy span').forEach((word, index) => {
            const word_arrive = ease_back(range(local, index * 0.08, 0.28 + index * 0.09));
            set_opacity(word, word_arrive);
            set_transform(word, `translateX(${lerp(index % 2 ? 90 : -90, 0, word_arrive)}px) skewX(${lerp(index % 2 ? -8 : 8, 0, word_arrive)}deg)`);
            word.style.filter = `blur(${lerp(10, 0, word_arrive)}px)`;
        });

        const scan = document.getElementById('signal_scan');
        const scan_progress = ease_in_out(range(local, 0.04, 0.88));
        scan.style.left = `${lerp(-80, 1340, scan_progress)}px`;
        set_opacity(scan, Math.sin(scan_progress * Math.PI));
        document.querySelector('.signal-watermark').style.transform = `translateX(${lerp(130, -50, local)}px)`;
    };

    const render_selector = time => {
        const local = range(time, 1.6, 4.8);
        const selector_layout = document.getElementById('selector_layout');
        const role_focus = document.getElementById('role_focus');
        const prompt_shell = document.getElementById('prompt_shell');
        const role_phase = range(local, 0.02, 0.56);
        const selector_exit = ease_in_out(range(local, 0.49, 0.68));

        const role_position = Math.min(3, role_phase * 4);
        document.querySelectorAll('.role-item').forEach((role, index) => {
            const y = 102 + ((index - role_position) * 72);
            const distance = Math.abs(index - role_position);
            role.style.top = `${y}px`;
            role.style.opacity = String(Math.max(0.16, 1 - distance * 0.33));
            role.style.filter = `blur(${Math.max(0, distance - 0.35) * 2.4}px)`;
            role.style.transform = `translateX(${distance < 0.48 ? 18 : 0}px) scale(${distance < 0.48 ? 1.04 : 0.94})`;
        });
        role_focus.style.top = `${100 + ((Math.round(role_position) - role_position) * 72)}px`;
        role_focus.style.boxShadow = `0 15px 50px rgba(226, 11, 23, ${0.1 + Math.sin(local * Math.PI * 9) * 0.04})`;
        set_opacity(selector_layout, 1 - selector_exit);
        set_transform(selector_layout, `translateY(${lerp(0, -70, selector_exit)}px) scale(${lerp(1, 0.82, selector_exit)})`);
        selector_layout.style.filter = `blur(${selector_exit * 12}px)`;

        const prompt_arrive = ease_back(range(local, 0.52, 0.73));
        set_opacity(prompt_shell, prompt_arrive);
        set_transform(prompt_shell, `translate(-50%, -50%) scale(${lerp(0.42, 1, prompt_arrive)}) rotateX(${lerp(15, 0, prompt_arrive)}deg)`);
        prompt_shell.style.clipPath = `inset(${lerp(44, 0, prompt_arrive)}% ${lerp(24, 0, prompt_arrive)}% round ${lerp(70, 30, prompt_arrive)}px)`;

        const prompt_html = 'Assemble an <strong>autonomous launch team</strong> and ship the product.';
        type_text(document.getElementById('prompt_copy'), prompt_html, range(local, 0.67, 0.9));

        const chips_progress = ease_back(range(local, 0.74, 0.92));
        document.querySelectorAll('.prompt-chips span').forEach((chip, index) => {
            const progress = ease_back(range(chips_progress, index * 0.14, 0.65 + index * 0.14));
            set_opacity(chip, progress);
            set_transform(chip, `translateY(${lerp(18, 0, progress)}px)`);
        });
        document.getElementById('prompt_submit').style.transform = `scale(${1 - Math.sin(range(local, 0.91, 0.99) * Math.PI) * 0.14})`;
    };

    const render_process = time => {
        const local = range(time, 4.8, 8);
        const stages = [
            {id: 'process_think', start: 0, end: 0.26},
            {id: 'process_research', start: 0.24, end: 0.51},
            {id: 'process_code', start: 0.49, end: 0.76},
            {id: 'process_design', start: 0.74, end: 1},
        ];
        stages.forEach((stage, index) => {
            const element = document.getElementById(stage.id);
            const visibility = segment_visibility(local, stage.start, stage.end, 0.045);
            const progress = range(local, stage.start, stage.end);
            set_opacity(element, visibility);
            set_transform(element, `translateX(${lerp(index % 2 ? 70 : -70, index % 2 ? -50 : 50, ease_in_out(progress))}px) scale(${lerp(1.08, 0.94, progress)})`);
            element.style.filter = `blur(${Math.max(0, (1 - visibility) * 13)}px)`;
        });
        document.querySelector('.mask-stream').style.transform = `translateX(${lerp(520, -620, range(local, 0.24, 0.51))}px)`;
        document.querySelector('.process-meta-a').style.transform = `translateY(${Math.sin(local * Math.PI * 5) * 10}px)`;
        document.querySelector('.process-meta-b').style.transform = `translateX(${lerp(80, -80, local)}px)`;
        document.querySelector('.remote-cursor').style.transform = `translate(${lerp(100, 0, ease_out(range(local, 0.78, 0.94)))}px, ${lerp(70, 0, ease_out(range(local, 0.78, 0.94)))}px)`;
        document.querySelector('.process-design-word .design-box').style.transform = `rotate(${lerp(-5, 1.5, range(local, 0.74, 1))}deg)`;
    };

    const render_orchestration = time => {
        const local = range(time, 8, 11.2);
        document.querySelectorAll('.operation-card').forEach((card, index) => {
            const arrive = ease_back(range(local, 0.03 + index * 0.075, 0.31 + index * 0.075));
            const base_y = index * 116;
            card.style.top = `${base_y}px`;
            set_opacity(card, arrive);
            set_transform(card, `translate(${lerp(170 + index * 20, 0, arrive)}px, ${lerp(-48, 0, arrive)}px) rotate(${lerp(index % 2 ? 4 : -4, 0, arrive)}deg)`);
            card.style.filter = `blur(${lerp(8, 0, clamp(arrive))}px)`;

            const state = card.querySelector('.operation-state');
            if (state) {
                const state_pulse = Math.max(0, Math.sin((local * 4 - index * 0.34) * Math.PI));
                state.style.transform = `scale(${1 + state_pulse * 0.08})`;
            }
        });

        const focus_position = Math.min(3, ease_in_out(range(local, 0.18, 0.68)) * 3);
        const focus = document.getElementById('operation_focus');
        set_opacity(focus, segment_visibility(local, 0.12, 0.78, 0.08));
        set_transform(focus, `translateY(${focus_position * 116}px) scaleX(${1 + Math.sin(focus_position * Math.PI) * 0.025})`);

        const toast_progress = ease_back(range(local, 0.54, 0.78));
        const toast = document.getElementById('operation_toast');
        set_opacity(toast, toast_progress * (1 - range(local, 0.88, 0.98)));
        set_transform(toast, `translateY(${lerp(55, 0, toast_progress)}px) scale(${lerp(0.88, 1, toast_progress)})`);

        const ray_progress = ease_in(range(local, 0.82, 1));
        const ray = document.getElementById('orchestration_ray');
        set_opacity(ray, ray_progress);
        set_transform(ray, `translate(-50%, -50%) scale(${lerp(0.1, 12, ray_progress)}) rotate(${lerp(-18, 8, ray_progress)}deg)`);
    };

    const render_network = time => {
        const local = range(time, 11.2, 14.4);
        const stage_arrive = ease_back(range(local, 0.01, 0.25));
        const network_stage = document.getElementById('network_stage');
        set_opacity(network_stage, stage_arrive);

        const portal_progress = ease_in(range(local, 0.82, 1));
        const orbit_rotation = local * 54;
        set_transform(network_stage, `translate(-50%, -50%) scale(${lerp(0.75, 1, stage_arrive) * lerp(1, 3.7, portal_progress)}) rotate(${orbit_rotation * 0.04}deg)`);
        document.querySelector('.orbit-a').style.transform = `translate(-50%, -50%) rotate(${orbit_rotation}deg)`;
        document.querySelector('.orbit-b').style.transform = `translate(-50%, -50%) rotate(${-orbit_rotation * 1.35}deg)`;

        document.querySelectorAll('.network-node').forEach((node, index) => {
            const arrive = ease_elastic(range(local, 0.05 + index * 0.025, 0.38 + index * 0.025));
            const angle = ((index / network_labels.length) * Math.PI * 2) - Math.PI / 2 + local * 0.25;
            const radius = index % 2 ? 218 : 176;
            const x = Math.cos(angle) * radius;
            const y = Math.sin(angle) * radius;
            const collapse = ease_in_out(range(local, 0.72 + (index % 3) * 0.018, 0.9));
            set_opacity(node, arrive * (1 - portal_progress));
            set_transform(node, `translate(${lerp(0, x, arrive) * (1 - collapse)}px, ${lerp(0, y, arrive) * (1 - collapse)}px) scale(${lerp(0.35, 1, arrive) * lerp(1, 0.25, collapse)}) rotate(${-orbit_rotation * 0.04}deg)`);
        });

        const counter_progress = ease_out(range(local, 0.18, 0.72));
        document.getElementById('network_count').textContent = Math.round(10000 * counter_progress).toLocaleString();
        const core = document.getElementById('network_core');
        set_transform(core, `translate(-50%, -50%) scale(${lerp(0.72, 1, stage_arrive) * lerp(1, 6.5, portal_progress)}) rotate(${-orbit_rotation * 0.04}deg)`);
        core.style.boxShadow = `0 0 0 ${lerp(18, 110, portal_progress)}px rgba(226, 11, 23, ${lerp(0.06, 0.16, portal_progress)}), 0 26px 70px rgba(226, 11, 23, 0.26)`;

        const copy = document.querySelector('.network-copy');
        set_opacity(copy, 1 - range(local, 0.72, 0.88));
        set_transform(copy, `translateX(${lerp(0, -90, portal_progress)}px)`);
    };

    const render_workspace = time => {
        const local = range(time, 14.4, 17.6);
        const reveal = ease_out(range(local, 0, 0.22));
        const scene = document.getElementById('scene_workspace');
        scene.style.clipPath = `circle(${lerp(0, 92, reveal)}% at 63% 50%)`;

        const camera = document.getElementById('workspace_camera');
        const camera_progress = ease_in_out(range(local, 0.06, 0.88));
        set_transform(camera, `translate(${lerp(72, -28, camera_progress)}px, ${lerp(24, -14, camera_progress)}px) scale(${lerp(0.87, 1.08, camera_progress)}) rotateX(${lerp(4, 0, reveal)}deg)`);

        const data_progress = ease_out(range(local, 0.18, 0.74));
        document.getElementById('workspace_live_count').textContent = String(Math.round(8 * data_progress));
        document.getElementById('status_ring').style.background = `conic-gradient(var(--agent-green) 0 ${data_progress * 288}deg, #e5e9e9 ${data_progress * 288}deg 360deg)`;
        document.getElementById('readiness_value').textContent = `${Math.round(98 * data_progress)}%`;
        document.getElementById('readiness_bar').style.width = `${98 * data_progress}%`;

        document.querySelectorAll('.activity-row').forEach((row, index) => {
            const row_progress = ease_back(range(local, 0.14 + index * 0.07, 0.38 + index * 0.07));
            set_opacity(row, row_progress);
            set_transform(row, `translateX(${lerp(60, 0, row_progress)}px)`);
        });
        document.querySelectorAll('.chart-bars span').forEach((bar, index) => {
            const bar_progress = ease_out(range(local, 0.28 + index * 0.025, 0.64 + index * 0.025));
            bar.style.transform = `scaleY(${bar_progress})`;
        });

        const pulse_progress = ease_out(range(local, 0.42, 0.72));
        const pulse = document.getElementById('workspace_pulse');
        const pulse_x = lerp(1120, 420, pulse_progress);
        const pulse_y = lerp(490, 240, pulse_progress);
        pulse.style.left = `${pulse_x}px`;
        pulse.style.top = `${pulse_y}px`;
        set_opacity(pulse, pulse_progress * (1 - range(local, 0.72, 0.86)));
        set_transform(pulse, `translate(-50%, -50%) scale(${lerp(0.4, 1.7, pulse_progress)})`);
    };

    const render_interface = time => {
        const local = range(time, 17.6, 20.8);
        document.querySelectorAll('.message-card').forEach((message, index) => {
            const arrive = ease_back(range(local, 0.03 + index * 0.11, 0.31 + index * 0.11));
            set_opacity(message, arrive);
            set_transform(message, `translateY(${lerp(48, 0, arrive)}px) scale(${lerp(0.94, 1, arrive)})`);
            message.style.filter = `blur(${lerp(7, 0, clamp(arrive))}px)`;
        });

        document.getElementById('research_state').textContent = local > 0.3 ? 'Ready' : 'Reasoning…';
        document.getElementById('build_state').textContent = local > 0.46 ? 'Verified' : 'Checking…';
        document.getElementById('review_state').textContent = local > 0.68 ? 'Ready' : 'Waiting';
        document.getElementById('system_load').style.width = `${lerp(22, 88, ease_in_out(range(local, 0.05, 0.7)))}%`;

        const composer_text = 'Launch the site and summarize what changed.';
        type_text(document.getElementById('composer_copy'), composer_text, range(local, 0.29, 0.56));
        document.getElementById('composer_submit').style.transform = `scale(${1 - Math.sin(range(local, 0.56, 0.66) * Math.PI) * 0.18})`;

        const output_progress = ease_back(range(local, 0.59, 0.82));
        const output = document.getElementById('generated_output');
        set_opacity(output, output_progress);
        set_transform(output, `translateY(${lerp(90, 0, output_progress)}px) rotateY(${lerp(12, 0, output_progress)}deg) scale(${lerp(0.72, 1, output_progress)})`);
        document.getElementById('generated_score').textContent = String(Math.round(98 * ease_out(range(local, 0.65, 0.9))));
        document.querySelectorAll('.generated-chart i').forEach((bar, index) => {
            const bar_progress = ease_out(range(local, 0.67 + index * 0.025, 0.89 + index * 0.025));
            bar.style.transform = `scaleY(${bar_progress})`;
        });
    };

    const render_depth = time => {
        const local = range(time, 20.8, 24);
        const copy = document.querySelector('.depth-copy');
        const copy_arrive = ease_out(range(local, 0.02, 0.28));
        set_opacity(copy, copy_arrive);
        set_transform(copy, `translateX(${lerp(-70, 0, copy_arrive)}px) scale(${lerp(0.93, 1, copy_arrive)})`);

        document.querySelectorAll('.float-card').forEach((card, index) => {
            const arrive = ease_back(range(local, 0.1 + index * 0.08, 0.38 + index * 0.08));
            const drift_x = Math.sin((local + index * 0.21) * Math.PI * 2) * (6 + index * 3);
            const drift_y = Math.cos((local + index * 0.19) * Math.PI * 2) * (8 + index * 4);
            set_opacity(card, arrive);
            set_transform(card, `translate3d(${lerp(180, drift_x, arrive)}px, ${lerp(index % 2 ? 120 : -100, drift_y, arrive)}px, ${index * 34}px) rotateY(${lerp(index % 2 ? -26 : 24, index % 2 ? 5 : -7, arrive)}deg) rotateZ(${index % 2 ? 3 : -3}deg) scale(${lerp(0.72, 1, arrive)})`);
        });

        document.querySelectorAll('.token').forEach((token, index) => {
            const [x, y, scale, angle, blur] = token_positions[index];
            const arrive = ease_back(range(local, 0.04 + index * 0.035, 0.36 + index * 0.035));
            const spin = lerp(90, 360 + angle, local);
            set_opacity(token, arrive);
            token.style.left = `${x}px`;
            token.style.top = `${y}px`;
            token.style.filter = `blur(${blur}px)`;
            set_transform(token, `translate(-50%, -50%) translateY(${Math.sin((local * 3 + index) * Math.PI) * 13}px) rotateY(${spin}deg) rotateZ(${angle}deg) scale(${scale * arrive})`);
        });

        document.querySelector('.halftone').style.transform = `translate(${lerp(60, -30, local)}px, ${lerp(-20, 25, local)}px) scale(${lerp(1.1, 0.95, local)})`;
        document.querySelector('.depth-rings').style.transform = `rotate(${local * 46}deg) scale(${1 + Math.sin(local * Math.PI * 2) * 0.06})`;
    };

    const render_clarity = time => {
        const local = range(time, 24, 27.2);
        const phrases = [
            {id: 'clarity_from', start: 0, end: 0.34, from: -160, to: 80},
            {id: 'clarity_to', start: 0.32, end: 0.67, from: 180, to: -80},
            {id: 'clarity_beat', start: 0.65, end: 1, from: 0, to: 0},
        ];
        phrases.forEach((phrase, index) => {
            const element = document.getElementById(phrase.id);
            const visibility = index === 2
                ? ease_out(range(local, phrase.start, phrase.start + 0.07))
                : segment_visibility(local, phrase.start, phrase.end, 0.06);
            const progress = range(local, phrase.start, phrase.end);
            set_opacity(element, visibility);
            set_transform(element, `translateX(${lerp(phrase.from, phrase.to, ease_in_out(progress))}px) scale(${lerp(1.18, 0.92, progress)})`);
            element.style.filter = `blur(${Math.max(0, (1 - visibility) * 12)}px)`;
        });

        document.querySelector('.clarity-echo-a').style.transform = `translateX(${lerp(180, -260, local)}px)`;
        document.querySelector('.clarity-echo-b').style.transform = `translateX(${lerp(-180, 240, local)}px)`;
        const rule = document.getElementById('clarity_rule');
        rule.style.width = `${ease_in_out(range(local, 0.36, 0.62)) * 620}px`;
        set_opacity(rule, 1 - range(local, 0.65, 0.72));
    };

    const render_invitation = time => {
        const local = range(time, 27.2, duration);
        const arrive = ease_out(range(local, 0.02, 0.34));
        const lockup = document.querySelector('.invitation-lockup');
        set_opacity(lockup, arrive);
        set_transform(lockup, `translateY(${lerp(42, 0, arrive)}px) scale(${lerp(0.94, 1, arrive)})`);
        lockup.style.filter = `blur(${lerp(12, 0, arrive)}px)`;
        document.querySelector('.invitation-orbit').style.transform = `translate(-50%, -50%) scale(${lerp(0.55, 1.08, ease_out(range(local, 0, 0.72)))})`;
        document.querySelector('.invitation-orbit').style.opacity = String(1 - range(local, 0.76, 1));
        document.getElementById('invitation_submit').style.transform = `scale(${1 - Math.sin(range(local, 0.7, 0.93) * Math.PI) * 0.1})`;
    };

    const render_cursor = time => {
        let opacity = 0;
        let x = 0;
        let y = 0;
        let scale = 1;
        let label = 'RUN';
        let flash = 0;
        let flash_x = 0;
        let flash_y = 0;

        if (time >= 3.55 && time <= 4.8) {
            const progress = ease_in_out(range(time, 3.55, 4.48));
            x = lerp(1190, 1064, progress);
            y = lerp(690, 538, progress);
            opacity = ease_out(range(time, 3.55, 3.75)) * (1 - range(time, 4.62, 4.8));
            scale = 1 - Math.sin(range(time, 4.42, 4.58) * Math.PI) * 0.12;
            label = 'BUILD';
            flash = Math.sin(range(time, 4.43, 4.67) * Math.PI);
            flash_x = 1093;
            flash_y = 560;
        } else if (time >= 18.82 && time <= 20.8) {
            const progress = ease_in_out(range(time, 18.82, 19.67));
            x = lerp(1210, 744, progress);
            y = lerp(670, 627, progress);
            opacity = ease_out(range(time, 18.82, 19.02)) * (1 - range(time, 20.56, 20.8));
            scale = 1 - Math.sin(range(time, 19.58, 19.76) * Math.PI) * 0.12;
            label = 'RUN';
            flash = Math.sin(range(time, 19.58, 19.86) * Math.PI);
            flash_x = 770;
            flash_y = 633;
        } else if (time >= 28.05 && time <= duration) {
            const progress = ease_in_out(range(time, 28.05, 28.68));
            x = lerp(1160, 893, progress);
            y = lerp(670, 438, progress);
            opacity = ease_out(range(time, 28.05, 28.23));
            scale = 1 - Math.sin(range(time, 28.62, 28.88) * Math.PI) * 0.1;
            label = 'NEXT';
            flash = Math.sin(range(time, 28.65, 28.98) * Math.PI) * 0.65;
            flash_x = 916;
            flash_y = 456;
        }

        set_opacity(global_cursor, opacity);
        set_transform(global_cursor, `translate(${x}px, ${y}px) scale(${scale})`);
        cursor_label.textContent = label;
        global_flash.style.left = `${flash_x}px`;
        global_flash.style.top = `${flash_y}px`;
        set_opacity(global_flash, flash);
        set_transform(global_flash, `translate(-50%, -50%) scale(${lerp(0.45, 1.35, flash)})`);
    };

    const render_at_time = input_time => {
        current_time = Math.max(0, Math.min(duration, Number(input_time) || 0));
        const active_scene = render_scene_visibility(current_time);

        render_signal(current_time);
        render_selector(current_time);
        render_process(current_time);
        render_orchestration(current_time);
        render_network(current_time);
        render_workspace(current_time);
        render_interface(current_time);
        render_depth(current_time);
        render_clarity(current_time);
        render_invitation(current_time);
        render_cursor(current_time);

        const atmosphere = document.getElementById('atmosphere');
        atmosphere.style.transform = `translate(${Math.sin(current_time * 0.34) * 24}px, ${Math.cos(current_time * 0.26) * 17}px) scale(${1.04 + Math.sin(current_time * 0.18) * 0.02})`;
        document.getElementById('ambient_grid').style.opacity = String(0.08 + Math.max(0, Math.sin(current_time * 0.55)) * 0.08);
        global_progress.style.width = `${(current_time / duration) * 100}%`;
        document.querySelector('.grain').style.transform = `translate(${(Math.floor(current_time * 30) % 5) * 1.5}%, ${(Math.floor(current_time * 24) % 7) * -1.2}%) rotate(5deg)`;

        timeline.value = String(current_time);
        time_current.textContent = current_time.toFixed(2);
        scene_label.textContent = active_scene.label;
        document.documentElement.style.setProperty('--timeline-time', String(current_time));
    };

    const stop = () => {
        playing = false;
        play_button.textContent = 'Play';
        cancelAnimationFrame(animation_frame);
        soundtrack.pause();
    };

    const tick = timestamp => {
        if (!playing) {
            return;
        }
        const elapsed = (timestamp - play_started_at) / 1000;
        const next_time = play_started_time + elapsed;
        if (next_time >= duration) {
            render_at_time(duration);
            stop();
            return;
        }
        render_at_time(next_time);
        animation_frame = requestAnimationFrame(tick);
    };

    const play = () => {
        if (playing) {
            stop();
            return;
        }
        if (current_time >= duration) {
            render_at_time(0);
        }
        playing = true;
        play_started_at = performance.now();
        play_started_time = current_time;
        play_button.textContent = 'Pause';
        soundtrack.currentTime = current_time;
        soundtrack.play().catch(() => {});
        animation_frame = requestAnimationFrame(tick);
    };

    timeline.addEventListener('input', event => {
        stop();
        render_at_time(event.target.value);
        soundtrack.currentTime = current_time;
    });
    play_button.addEventListener('click', play);
    mute_button.addEventListener('click', () => {
        soundtrack.muted = !soundtrack.muted;
        mute_button.textContent = soundtrack.muted ? '×' : '♪';
        mute_button.setAttribute('aria-label', soundtrack.muted ? 'Unmute soundtrack' : 'Mute soundtrack');
    });
    window.addEventListener('resize', fit_stage);

    const params = new URLSearchParams(window.location.search);
    const render_mode = params.get('render') === '1';
    if (render_mode) {
        document.body.classList.add('render-mode');
    }

    let initial_time = Number(params.get('t') || 0);
    if (params.has('frame')) {
        const fps = Number(params.get('fps') || 60);
        initial_time = Number(params.get('frame')) / fps;
    }

    window.render_at_time = render_at_time;
    window.motion_duration = duration;
    window.motion_ready = false;

    fit_stage();
    render_at_time(initial_time);
    document.fonts.ready.then(() => {
        window.motion_ready = true;
        document.body.dataset.motionReady = 'true';
        if (params.get('autoplay') === '1' && !render_mode) {
            play();
        }
    });
})();
