import '../../src/css/style.css';
import '../../../node_modules/lightgallery/css/lightgallery-bundle.min.css';
import _, {findIndex} from 'lodash';
import {styles} from "./mapStyles";
import animations from './animations';
import xatos from "./xatos";

import lightGallery from "lightgallery";
import lgZoom from 'lightgallery/plugins/zoom';

//out vars
declare const screenWidth: any;
declare const sel: any;
declare const selAll: any;
declare const mainIcon: any;
declare const google: any;
declare const otherLocations: any;
declare const nearbyLocations: any;
declare const Splide: any;
//

//map
declare const lat: string;
declare const lng: string;
//

//custom types
type State = 'init' | 'click'; //custom literal union
type GalleryState = 'gallery' | 'carousel'; //custom literal union
//

window.addEventListener('load', () => {

    xatos();

    //map
    if (sel('.top-block-map')) {
        const coordinates = new google.maps.LatLng({
            lat: parseFloat(lat),
            lng: parseFloat(lng)
        });

        let zoom = 12.8;
        if (screenWidth.matches) zoom = 11.75;

        console.log(zoom);

        const map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
            center: coordinates,
            zoom,
            styles,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
        });

        let mainMarkerSize = [119, 68.6];
        if (screenWidth.matches < 1024) mainMarkerSize = [109, 61];

        const marker = new google.maps.Marker({
            position: coordinates,
            map,
            animation: google.maps.Animation.DROP,
            icon: {
                origin: new google.maps.Point(0, 0),
                url: mainIcon,
                scaledSize: new google.maps.Size(...mainMarkerSize),
                anchor: new google.maps.Point(0, 66),
            },
        });

        const singleSlides = selAll('.top-block-map .single-slide');
        let markers: any = [];
        const infowindow = new google.maps.InfoWindow({
            pixelOffset: new google.maps.Size(0, -3),
        });

        const attachMessage = function (marker: any, message: any, index: any, pos: any) {
            marker.addListener("mouseover", () => {
                infowindow.setContent(message);
                infowindow.open(map, marker);

                setTimeout(() => {
                    if (sel('.gm-style-iw')) {
                        const toolTips = document.querySelector('.gm-style-iw-t')! as HTMLParagraphElement;
                        toolTips.style.animation = 'infoWindow 0.3s ease-out forwards';
                    }
                });
            });
            marker.addListener("mouseout", () => {
                infowindow.close(map, marker);
            });

            marker.addListener("click", () => {
                infowindow.setContent(message);
                infowindow.open(map, marker);

                setTimeout(() => {
                    if (sel('.gm-style-iw')) {
                        const toolTips = document.querySelector('.gm-style-iw-t')! as HTMLParagraphElement;
                        toolTips.style.animation = 'infoWindow 0.3s ease-out forwards';
                    }
                });
            });
        }

        const parseLocations = function (locations: any, index: any, map: any) {
            _.each(markers, marker => {
                if (marker && marker.setMap)
                    marker.setMap(null);
            });

            _.each(locations[index], location => {
                _.each(location, ({name, coordinates, icon}, i: number) => {
                    if (!coordinates || !icon) return;

                    const position = new google.maps.LatLng({
                        lat: parseFloat(coordinates.latitude),
                        lng: parseFloat(coordinates.longitude)
                    });

                    setTimeout(() => {
                        const marker = new google.maps.Marker({
                            position,
                            animation: google.maps.Animation.DROP,
                            icon: {
                                url: icon,
                                scaledSize: new google.maps.Size(33, 33),
                            },
                            map,
                        });

                        attachMessage(marker, name, i, position);
                        markers.push(marker);
                    }, i * 100);
                });
            });
        }

        const addLocations = function (state: State, locations: any, map: any, index?: any, slides?: any) {
            switch (state) {
                case 'init':
                    const findActive = _.find(slides, slide => slide.classList.contains('active'));
                    index = [...slides].indexOf(findActive);
                    parseLocations(locations, index, map);
                    break;
                case 'click':
                    parseLocations(locations, index, map);
                    break;
            }
        }

        addLocations('init', nearbyLocations, map, 0, singleSlides);
        _.each(singleSlides, (slide, i) => slide.addEventListener('click', () => {
            if (slide.classList.contains('pressed')) return;

            _.each(singleSlides, slide => slide.classList.remove('pressed'));
            slide.classList.add('pressed');

            addLocations('click', nearbyLocations, map, +i);
        }));

        const arr: any = [];

        const expandSingleClick = function () {
            // @ts-ignore
            const {lat, lng} = this.dataset;
            const coordinates = new google.maps.LatLng({
                lat: parseFloat(lat),
                lng: parseFloat(lng)
            });

            const allExpands = selAll('.single-expanded.current-slide');
            const single =  _.uniq(arr);

            const findExpand = _.findIndex(single, expand => {
                // @ts-ignore
                if (expand === this)
                    return expand;
            });

            map.panTo(coordinates);
            google.maps.event.trigger(markers[findExpand], 'click');
        }

        _.each(singleSlides, slide => slide.addEventListener('click', () => {
            const expands = slide.querySelectorAll('.single-expanded');

            _.each(expands, exp => {
                arr.push(exp);
            });

            _.each(arr, exp => {
                exp.classList.add('current-slide');

                exp.removeEventListener('click', expandSingleClick);
                exp.addEventListener('click', expandSingleClick);
            });
        }));

        singleSlides[0].click();
    }
    //

    const lgInit = function (state: GalleryState = 'gallery', lgItems: string, listenItems: string): void {
        if (!sel('.page-gallery') && !sel('.page-home') && !sel('.single-namas')) return;

        const getGallery = document.getElementById('lightgallery')!;
        const mainItems = selAll(lgItems)!;
        const otherItems = selAll(listenItems)!;

        let speed = 700;

        lightGallery(getGallery, {
            // plugins: [lgZoom],
            speed,
            mode: 'lg-fade',
            download: false,
            
        });

        _.each(otherItems, (item, i: number) => item.addEventListener('click', () => {
            if (_.includes(state, 'gallery'))
                mainItems[i].click();
            else
                mainItems[item['dataset']['index']].click();

            //fix
            _.each(otherItems, item => {
                item.style.pointerEvents = 'none';
            });

            setTimeout(() => {
                _.each(otherItems, item => {
                    item.style.pointerEvents = 'all';
                });
            }, speed * 2.5);
            //
        }));
    }

    if (sel('.page-home')) {
        const grid = sel('.grid-images .gallery');
        const gridImages = selAll('.grid-images img');
        grid.innerHTML = '';

        for (let i = 0; i < gridImages.length; i++) {
            for (let j = 0; j < gridImages.length / 6; j++) {
                let cloned = gridImages[j].cloneNode(false);
                // data-aos-delay="' . $delay * $counter . '" data-aos-offset="' . $offset . '" data-aos="fade-right"
                cloned.setAttribute('data-aos-delay', `${Math.floor(Math.random() * (8 - 2) + 2)}00`);
                cloned.setAttribute('data-aos-offset', 200);
                cloned.setAttribute('data-aos', 'fade-up');

                cloned.setAttribute('data-index', j);
                grid.insertAdjacentElement('beforeend', cloned);
            }
        }

        lgInit('carousel', '#lightgallery > a', '.gallery > img');
    }

    if (sel('.page-gallery')) {
        lgInit('gallery', '#lightgallery > a', '.content-grid .grid-item');
    }

    if (sel('.single-namas')) {
        let splideGallery = new Splide('.splide-gallery', {
            type: 'loop',
            perPage: 3,
            perMove: 1,
            speed: 600,
            easing: 'cubic-bezier(0.445, 0.05, 0.55, 0.95)',
            pagination: true,
            focus: 0,
            slideFocus: true,
            arrows: false,
            gap: 30,
            autoWidth: true,
            autoHeight: true,
            breakpoints: {
                769: {
                    gap: 16,
                },
            }
        }).mount();

        lgInit('carousel', '#lightgallery > a', '.carousel-block .splide__slide');
    }

    if (sel('.splide-projects')) {
        const splideProjects = selAll('.splide-projects');

        _.each(splideProjects, project => {
            new Splide(project, {
                type: 'loop',
                perPage: 2,
                perMove: 1,
                speed: 600,
                easing: 'cubic-bezier(0.445, 0.05, 0.55, 0.95)',
                pagination: true,
                focus: 0,
                arrows: false,
                gap: 30,
                width: '60.67vw',
                breakpoints: {
                    769: {
                        gap: 16,
                    },
                }
            }).mount();
        });
    }

    if (sel('.projects-block')) {
        const photos = selAll('.single-photo');

        _.each(photos, photo => {
            photo.addEventListener('mouseover', () => {
                photo.classList.add('active');
            });

            photo.addEventListener('mouseout', () => {
                photo.classList.remove('active');
            });
        });
    }

    animations();

    //privacy
    if (sel('.privacy-policy-page')) {
        const tables = selAll('.main-content .text table');

        _.each(tables, table => {
            const div = document.createElement('div');
            const point = document.createElement('div');

            point.classList.add('table-point');
            div.classList.add('privacy-table');

            table.insertAdjacentElement('beforebegin', point);
            div.insertAdjacentElement('beforeend', table);
            point.insertAdjacentElement('afterend', div);
        });
    }
    //
});
//
// class Vehicle {
//     //prop not based on created object
//     // color: string = 'red';
//     //
//     constructor(color: string){
//         //prop based on created object
//         this.color = color;
//     }
//
//     // constructor(public color: string){
//     //
//     // }
//
//     drive(): void{
//         console.log('driving');
//     }
//
//     protected honk(): void {
//         console.log('honk');
//     }
//
//     startDrivingProcess(): void {
//         this.drive();
//     }
// }
//
// //inheritance between prototype classes
// class Car extends Vehicle{
//     drive(): void{
//         console.log('redefined driving');
//     }
//
//     startDrivingProcess() {
//         this.honk();
//     }
// }
//
// const car = new Car('Blue');
// car.startDrivingProcess()
//
// console.log(car);



