'use strict';

import {Controller} from '@hotwired/stimulus';
import MagicGrid from 'magic-grid';

export default class extends Controller {
    private grid: MagicGrid | null = null;

    connect(): void {
        const container = this.element as HTMLElement;
        this.grid = new MagicGrid({
            container: container,
            animate: true,
            gutter: 26,
            static: true,
            useMin: false,
        });

        this.grid.listen();
    }

    /**
     * Re-run the layout after cards have been hidden/shown (e.g. by the
     * wishlists controller filtering client-side). Without this, magic-grid
     * leaves gaps where the hidden cards used to be.
     */
    relayout(): void {
        // magic-grid's listener for `resize` calls positionItems internally.
        window.dispatchEvent(new Event('resize'));
    }
}
