$(() => {
    $('.loader-container').show();
    validateLoginStatus(() => {
        getDashboardData();
    }, () => {
        requireLogin();
    });
});

function getDashboardData() {
    $.get(DASHBOARD_DATA_URL, (resp) => {
        $('.loader-container').hide();
        $('.dashboard__content-wrapper').append(resp).promise().done(() => {
            if (resp == '') {
                requireLogin();
            } else if ($('.errorMsg').length > 0) {
                $('.dashboard__content-wrapper').html($('#highload').html());
            } else if (resp == 'Maintenance') {
                $('.dashboard__content-wrapper').html($('#maintenance-popup').html());
            } else if (resp == 'Unexpected Error') {
                $('.dashboard__content-wrapper').html($('#general-error').html());
            } else {
                // E-letter
                if ($('#eletterUrl').val()) {
                    $('#quick-access-eletter').attr('href', $('#eletterUrl').val());
                }
                if ($('#eletterCount').val()) {
                    $('#quick-access-eletter .numberCircle > span').text($('#eletterCount').val());
                    $('#quick-access-eletter .numberCircle').show();
                }

                // EV
                if ($('#showEV').val() === 'Y') {
                    $('#quick-access-ev').show();
                }

                // Move sections to respective containers
                $('#welcome-container').html($('.dashboard__welcome-wrapper'));
                $('#notification-container').html($('.dashboard__notifications-wrapper'));
                $('#vehicle-container').html($('.dashboard__vehicle-wrapper'));
                $('#profile-container').html($('.dashboard__personal-wrapper'));

                dashboardNotificationCard();
                dialog();
                readMore();

                initVehicleAndAssets();
            }
        });
    });
}

function initVehicleAndAssets() {
    $('.tabs-link').click(function () {
        $('.tabs-link').removeClass('active');
        $(this).addClass('active');
        $('.tabs-content').removeClass('active');
        $('#' + $(this).data('tabId')).addClass('active');

        // Remove 2nd tab when on list mode
        if ($(this).data('tabId') === 'tab-all-assets') {
            $('.tabs-link:eq(1)').remove();
        }
    });
    initDataTable4MoreAssets();
}

function initDataTable4MoreAssets() {
    $('#veh_loading').append($('#highload-popup').html());
    $('#veh_loading .highload_btn').click(function () {
        $('#veh_loading').removeClass('active');
        $('#veh_loading .animation_loading').show();
        $('#veh_loading .highload_popup').hide();
    });
    $('#tbl-fleet tr').click(function () {
        let tabId = $(this).data('tabId');
        let assetNumber = $(this).data('assetNumber');
        let assetTypeCode = $(this).data('assetTypeCode');
        let assetTypeDesc = $(this).data('assetTypeDesc');

        let switchTab = () => {
            $('.tabs-link, .tabs-content').removeClass('active');
            $('#vehicle-tabs').append(`<li class="tabs-link active" data-tab-id="${tabId}"><a href="javascript:void(0)">${assetTypeDesc ? assetTypeDesc + ': ' : ''}${assetNumber}</a></li>`);
            $('#' + tabId).addClass('active');
            $('.dashboard__content-with-tabs')[0].scrollIntoView();
            window.scrollBy(0, -150);
        };

        if (assetNumber) {
            if ($('#' + tabId).length) {
                switchTab();
            } else {
                $('#veh_loading').addClass('active');
                $.get('/vrls/vrl/getAssetDetails', {
                    type: assetTypeCode,
                    assetNo: assetNumber
                }).done((resp) => {
                    if (resp.indexOf('tabs-content') == -1) { // Error
                        resp = `<div id="tab-${assetNumber}" class="tabs-content active"><div class="row dashboard--content"><div>${resp}</div></div></div>`;
                    }
                    $('#m5-vehicle-content').append(resp);
                    $('#veh_loading').removeClass('active');
                    $('.nonlogin').remove();
                    $('.displayError').remove();
                    switchTab();
                }).fail(() => {
                    $('#veh_loading .animation_loading').hide();
                    $('#veh_loading .highload_popup').show();
                });
            }
        }
    });

    new DataTable('#tbl-fleet', {
        language: {
            search: '_INPUT_',
            searchPlaceholder: 'Search'
        },
        layout: {
            bottomEnd: {
                paging: {
                    firstLast: false
                }
            }
        },
        initComplete: (settings, json) => {
            $('#tbl-fleet').show();
        }
    });
}

function requireLogin() {
    const PARAMS = new URLSearchParams(window.location.search);
    essoLogin(PARAMS.get(PARAM_IDP));
}


/*=========================================================
    2. Dashboard - Notification card height
=========================================================*/
const dashboardNotificationCard = () => {
    const containers = document.querySelectorAll('.dashboard__banner-columns')

    containers.forEach((container) => {
        const notification = container.querySelector(
            '.dashboard__notifications-wrapper'
        )

        const updateHeight = () => {
            notification.style.setProperty('--notification-card-max-height', `26rem`)

            if (container.offsetHeight > notification.offsetHeight) {
                notification.style.setProperty(
                    '--notification-card-max-height',
                    `${container.offsetHeight}px`
                )
            }
        }

        updateHeight()

        addEventListener('resize', updateHeight)
    })
}

/*=========================================================
    3. Dashboard - Quick Access (pop-up dialog)
=========================================================*/
const dialog = () => {
    const showButtons = document.querySelectorAll('[data-dialog]')

    showButtons.forEach((showButton) => {
        const dialogTarget = showButton.getAttribute('data-dialog-target')

        const dialog = dialogTarget
            ? document.querySelector(`#${dialogTarget}`)
            : null

        if (!dialog) return

        const dialogBody = dialog.querySelector(`.dialog__body__content`)
        const closeButton = dialog.querySelector(`.dialog__close-button`)

        // Click to show dialog
        showButton.addEventListener('click', (event) => {
            event.preventDefault()

            dialog.classList.add('opening')
            dialog.showModal()

            setTimeout(() => {
                dialog.classList.remove('opening')
            }, 300)

            dialogBody && dialogBody.scrollTo(0, 0)
            document.body.style.overflow = 'hidden'
        })

        // Click to close dialog
        closeButton.addEventListener('click', (event) => {
            event.preventDefault()

            dialog.classList.add('closing')

            setTimeout(() => {
                dialog.close()
                dialog.classList.remove('closing')
            }, 500)

            document.body.style.overflow = ''
        })

        addEventListener('resize', () => {
            if (
                dialog.getAttribute('data-breakpoint') === 'max-768px' &&
                window.innerWidth >= 768
            ) {
                document.body.style.overflow = ''
            }
        })
    })
}

/*=========================================================
    4. Expand or collapse 'Read more content'
=========================================================*/
const readMore = () => {
    const truncateText = (
        container,
        text,
        textOnly,
        maxTextLength,
        maxTextLengthMobile
    ) => {
        // Create ellipsis
        let ellipsis = document.createElement('span')
        ellipsis.innerText = '...'

        // Truncate text
        let textLength = maxTextLengthMobile
        let truncatedText = container.innerHTML.substring(0, textLength)

        if (window.innerWidth >= 768) {
            textLength = maxTextLength
        }

        // Create read more button
        const readMoreButton = createReadMoreButton(container, text, truncatedText)

        if (textOnly.length > textLength) {
            // Show truncated text
            container.innerHTML = truncatedText
            container.append(ellipsis)
            container.append(readMoreButton)
        } else {
            // Show full text
            container.innerHTML = text
            ellipsis.remove()
            readMoreButton.remove()
        }
    }

    const createReadMoreButton = (container, text, truncatedText) => {
        // Create ellipsis
        let ellipsis = document.createElement('span')
        ellipsis.innerText = '...'

        // Create read more button
        const readMoreButton = document.createElement('a')
        readMoreButton.setAttribute('href', '#')
        readMoreButton.setAttribute('role', 'button')
        readMoreButton.setAttribute('aria-expanded', 'false')
        readMoreButton.setAttribute('data-read-more-button', '')
        readMoreButton.style.whiteSpace = 'no-wrap'
        readMoreButton.innerText = 'Read more'

        // Click to show more text
        readMoreButton.addEventListener('click', (event) => {
            event.preventDefault()

            if (readMoreButton.getAttribute('aria-expanded') === 'false') {
                // Show full text
                container.innerHTML = text
                ellipsis.remove()
                readMoreButton.innerText = 'Read less'
                container.append(readMoreButton)
                readMoreButton.setAttribute('aria-expanded', 'true')
            } else {
                // Show truncated text
                container.innerHTML = truncatedText
                container.append(ellipsis)
                readMoreButton.innerText = 'Read more'
                container.append(readMoreButton)
                readMoreButton.setAttribute('aria-expanded', 'false')
            }
        })

        return readMoreButton
    }

    const containers = document.querySelectorAll('[data-read-more]')

    containers.forEach((container) => {
        const text = container.innerHTML
        const textOnly = container.innerText
        let customMaxTextLength = container.getAttribute('data-read-more-text')
        let customMaxTextLengthMobile = container.getAttribute(
            'data-read-more-text-m'
        )
        let maxTextLength = 300
        let maxTextLengthMobile = 300

        if (customMaxTextLength) {
            customMaxTextLength = parseInt(customMaxTextLength)

            if (!Number.isNaN(customMaxTextLength)) {
                maxTextLength = customMaxTextLength
            }
        }

        if (customMaxTextLengthMobile) {
            customMaxTextLengthMobile = parseInt(customMaxTextLengthMobile)

            if (!Number.isNaN(customMaxTextLengthMobile)) {
                maxTextLengthMobile = customMaxTextLengthMobile
            }
        }

        truncateText(container, text, textOnly, maxTextLength, maxTextLengthMobile)

        addEventListener('resize', () =>
            truncateText(
                container,
                text,
                textOnly,
                maxTextLength,
                maxTextLengthMobile
            )
        )
    })
}

function initCarousel(sel, config) {
    if (config) {
        sel.slick(config);
    } else {
        sel.slick();
    }
}

$(window).on('load resize orientationchange', (function () {
    $('.dashboard__carousel').not('.slick-initialized').each((function () {
        var $carousel = $(this);
        initCarousel($carousel, {
            autoplay: true,
            autoplaySpeed: 5000, // NEW: Changed from 3000 to 5000
            arrows: false,
            // prevArrow: '<button type="button" class="slick-prev pull-left"><i class="fa fa-chevron-left" aria-hidden="true"></i></button>',
            // nextArrow: '<button type="button" class="slick-next pull-right"><i class="fa fa-chevron-right" aria-hidden="true"></i></button>',
            dots: true,
            // dotsClass: 'slides-pagination',
            infinite: true,
            initialSlide: 0,
            speed: 300,
            slidesToShow: 1,
            slidesToScroll: 1,
            swipe: true,
            mobileFirst: true,
            centerMode: true,
            centerPadding: '0px', // NEW: Changed from '10px' to '0px'
            appendArrows: $(this).parent().find('.dashboard__carousel__indicators__container'), // NEW: Added for new arrow and dots position 
            appendDots: $(this).parent().find('.dashboard__carousel__indicators__container'), // NEW: Added for new arrow and dots position 
            responsive: [{
                breakpoint: 768,
                settings: {
                    arrows: true,
                    centerMode: false,
                    slidesToShow: 1
                }
            }]
        });
    }));
}));