import './styles/pages/_about.scss';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { HorizontalPinScroll } from './animations/gsap/HorizontalPinScroll';

document.addEventListener('DOMContentLoaded', () => {
    const bg = document.querySelector<HTMLElement>('[data-about-bg="true"]');

    if (!bg) {
        return; // Not on the About page.
    }

    gsap.registerPlugin(ScrollTrigger);

    // Same ambient scroll effect as assets/actualite.ts: the fixed mountain-mask
    // backdrop settles into place and warms up to the lighter beige tone as the
    // visitor scrolls through the page.
    gsap.fromTo(bg,
        { y: 0 },
        {
            y: 250,
            // backgroundColor: '#f9f2eb',
            ease: 'none',
            scrollTrigger: {
                trigger: document.body,
                start: 'top top',
                end: 'bottom bottom',
                scrub: true,
            },
        }
    );

    initGaltaHorizontalScroll();
});

/**
 * "C'est quoi galta ?": the line of items is wider than the screen -> pin the section and let the
 * mouse wheel scrub it sideways, like the home's mountain sections. Skipped in edit mode (grid
 * layout) and when everything already fits (nothing to scroll: no pin, no dead scroll distance).
 * When the pin isn't created (reduced motion, fits at load) `.about-galta__viewport` stays a
 * native `overflow-x: auto` scroller.
 */
function initGaltaHorizontalScroll(): void {
    if (document.body.dataset.editorMode === 'true') {
        return;
    }

    const pin = document.querySelector<HTMLElement>('.about-galta__pin');
    const viewport = pin?.querySelector<HTMLElement>('.about-galta__viewport');
    const track = pin?.querySelector<HTMLElement>('[data-horizontal-track]');
    if (!pin || !viewport || !track || track.scrollWidth <= viewport.clientWidth) {
        return;
    }

    new HorizontalPinScroll({
        pinTarget: pin,
        trackTarget: track,
        triggerTarget: pin.querySelector<HTMLElement>('.about-galta__title') ?? pin,
    }).play();

    // Late images / webfonts change the track width after load: re-measure (same as home.ts).
    window.addEventListener('load', () => ScrollTrigger.refresh(), { once: true });
    void document.fonts?.ready?.then(() => ScrollTrigger.refresh());
}
