let WorkTypeColor = [];
var eventsArray = []
var baseAPIUrl = '';
var publisherId = '';
var extensionId = '';
var calendar = null;
var userguidelink = "";
var userhelplink = "";
let tempHighlightEvent = null;
var azureAuthenticationHeader = '';
var organizationName = '';
var isOrgLicenseValid = true;

function showCalendarTrialPill(message) {
    $("#calendarTrialPillText").text(message);
    $("#calendarTrialPill").show();
    $("#startTrialMessage").hide();
}

function hideCalendarTrialPill() {
    $("#calendarTrialPill").hide();
}

function setButtonState(buttonSelector, isEnabled) {
    const btn = typeof buttonSelector === 'string'
        ? document.querySelector(buttonSelector)
        : buttonSelector;
    if (!btn) return;

    btn.disabled = !isEnabled;
    btn.style.opacity = isEnabled ? '1' : '0.5';
    btn.style.cursor = isEnabled ? 'pointer' : 'not-allowed';
}

const fieldName = "ptUserType";
let canLogTime = false;
IndexLibrary.InitializeSDK().then(function () {
    Load();
});

async function Load() {
    azureAuthenticationHeader = await IndexLibrary.GetAccessToken();
    const config = await IndexLibrary.GetExtensionConfig();
    baseAPIUrl = config.apiBaseUrl;
    publisherId = config.publisherId;
    extensionId = config.extensionId;
    userguidelink = config.userguidelink;
    userhelplink = config.userhelplink;
    organizationName = await IndexLibrary.GetAccountNameAsync();
    hideCalendarTrialPill();

    try {
        const getLicenseResponse = await IndexLibrary.PostRequest({
            endpoint: '/api/License/GetLicense',
            body: { organizationName: organizationName }
        });

        if (getLicenseResponse.status == 404) {
            isOrgLicenseValid = false;
            hideCalendarTrialPill();
            $("#startTrialMessage").show();
            CreateTrialLicense();
        } else {
            const licenseData = await getLicenseResponse.json();
            if (licenseData.status !== undefined && licenseData.status == 404) {
                isOrgLicenseValid = false;
                hideCalendarTrialPill();
                $("#startTrialMessage").show();
                CreateTrialLicense();
            } else {
                const userLicenseResponse = await IndexLibrary.GetRequest({
                    endpoint: `/api/License/IsUserLicensed?organizationName=${organizationName}&email=${IndexLibrary.GetUserEmail()}&moduleUserType=ptUserType`
                });
                const isUserLicensed = await userLicenseResponse.text();

                if (isUserLicensed.toLowerCase() == 'false') {
                    isOrgLicenseValid = false;
                    hideCalendarTrialPill();
                    $("#authorizationErrorMessage").show();
                    $("#authorizationErrorMessage").text("You are not authorized to perform this action. Please contact your organization administrator.");
                    $("#startTrialMessage").hide();
                } else if (licenseData.licenseType == 0) {
                    var licenseExpiryDate = new Date(licenseData.expiryDateTimeUtc);
                    if (licenseExpiryDate < new Date()) {
                        isOrgLicenseValid = false;
                        hideCalendarTrialPill();
                        $("#startTrialMessage").show();
                        $("#startTrialMessage").text("Your license is invalid or expired. Please contact your organization administrator.");
                    } else {
                        isOrgLicenseValid = true;
                        showCalendarTrialPill("Trial valid till " + licenseExpiryDate.toLocaleDateString("en-US"));
                    }
                } else {
                    isOrgLicenseValid = true;
                    hideCalendarTrialPill();
                    $("#startTrialMessage").hide();
                }
            }
        }
    } catch (error) {
        isOrgLicenseValid = false;
        hideCalendarTrialPill();
        $("#startTrialMessage").show();
    }

    azureAuthenticationHeader = await IndexLibrary.GetAccessToken();
    GetProjectTimesheetsByUserEmail();



}

async function CreateTrialLicense() {

    await IndexLibrary.AutoCreateTrialLicense();
}

async function UpdateTimesheet(info) {
    let startdate = new Date(info.event.start);
    let enddate = new Date(info.event.end);
    var options = {
        year: "numeric",
        month: "numeric",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        hour12: false
    };
    let startdateStr = Intl.DateTimeFormat("en-US", options).format(startdate);
    let enddateStr = Intl.DateTimeFormat("en-US", options).format(enddate);

    IndexLibrary.PostRequest({
        endpoint: '/api/Timesheet/UpdateTimesheet',
        body: {
            organizationName: organizationName,
            timesheetId: info.event.id.toString(),
            workItemId: info.event.extendedProps.workItemId,
            workStarted: IndexLibrary.convertLocalToUtc(startdateStr),
            workEnded: IndexLibrary.convertLocalToUtc(enddateStr),
            trackingWorkItemTypeId: info.event.extendedProps.workTypeId,
            description: info.event.extendedProps.workDescription,
            isBillable: info.event.extendedProps.isBillable,
            UpdatedBy: IndexLibrary.GetUserEmail()
        }
    })
        .then((response) => response.json())
        .then(async function (json) {
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });

            Toast.fire({
                icon: 'success',
                title: 'Time updated successfully'
            });
            //Refresh calendar after the Drag update
            GetProjectTimesheetsByUserEmail();
        });

}

async function GetProjectTimesheetsByUserEmail() {
    eventsArray = [];
    var currentProjectName = await IndexLibrary.GetCurrentProjectName();
    var currentProjectId = await IndexLibrary.GetCurrentProjectId();
    IndexLibrary.PostRequest({
        endpoint: '/api/Timesheet/GetTimesheetsByProjectId',
        body: {
            OrganizationName: organizationName,
            ProjectId: currentProjectId,
            ProjectName: currentProjectName,
            UserEmail: IndexLibrary.GetUserEmail()
        }
    })
        .then((response) => response.json())
        .then(async function (json) {
            if (json.length > 0) {

                json.forEach(workItemObj => {
                    var dtStart = new Date(IndexLibrary.convertUtcToLocal(workItemObj.workStarted));
                    var dtEnd = workItemObj.workEnded
                        ? new Date(IndexLibrary.convertUtcToLocal(workItemObj.workEnded))
                        : null;

                    var isActive = !dtEnd;

                    var workItemTitle = workItemObj.workItemTitle || "";
                    var className = 'totalHours-' + dtStart.toLocaleDateString('en-GB').replaceAll('/', '-');
                    var hoursWorked = 0;
                    if (dtEnd) {
                        hoursWorked = parseFloat(Math.abs(dtEnd - dtStart) / 36e5);
                    }

                    eventsArray.push({
                        id: workItemObj.timesheetId,
                        title: workItemTitle,
                        start: dtStart.toISOString(),
                        end: dtEnd ? dtEnd.toISOString() : dtStart.toISOString(),
                        extendedProps: {
                            timesheetId: workItemObj.timesheetId,
                            headerClass: className,
                            workItemTitle: workItemTitle,
                            hours: hoursWorked,
                            workType: workItemObj.workType,
                            workDescription: workItemObj.description,
                            isBillable: workItemObj.isBillable,
                            workTypeId: workItemObj.trackingWorkTypeId,
                            workItemId: workItemObj.workItemId,
                            workItemProject: workItemObj.projectName || "",
                            isActive: isActive
                        }
                    });
                });
                InitializeCalendar();
                applyLogTimePermission();
            } else {
                InitializeCalendar();
                applyLogTimePermission();
            }
        })
    await LoadWorkTypeColors();
}
function InitializeCalendar() {
    var calendarEl = document.getElementById('calendar');

    if (calendar) {
        calendar.removeAllEvents();
        document.querySelectorAll('[class^="totalHours-"]').forEach(el => {
            el.innerText = 'Total Hours: 0';
        });
        calendar.addEventSource(eventsArray);
        return;
    }
    calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'timeGridWeek',
        themeSystem: 'bootstrap',
        editable: isOrgLicenseValid,
        customButtons: {
            logTime: {
                text: 'Log time',
                click: function () {


                    if (typeof IndexLibrary.HandleTimeTrackingMenuOptionClick === 'function') {
                        IndexLibrary.HandleTimeTrackingMenuOptionClick({

                            timesheetTable: $("#timesheetsTable"),
                            totalLoggedHoursLabel: $("#workitem-page-logged-hours-button"),
                            apiUrl: baseAPIUrl,
                            azureAuthenticationHeader: azureAuthenticationHeader,
                            EditWorkItem: true
                        });
                    }
                }
            },

            moreOptions: {
                text: '⋮'
            }
        },
        headerToolbar: {
            left: 'prev,next today logTime',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek moreOptions'
        },
        editable: true,
        events: eventsArray,

        // Custom rendering of events
        eventContent: function (arg) {
            let container = document.createElement('div');
            container.style.display = 'flex';
            container.style.flexDirection = 'column';
            container.style.gap = '2px';

            const workItemId = arg.event.extendedProps.workItemId || arg.event.id || '';
            const workItemTitle = arg.event.extendedProps.workItemTitle || 'Add Event';

            const isWeekOrDayView = arg.view.type === 'timeGridWeek' || arg.view.type === 'timeGridDay';

            // Work Item ID + Title
            let link = document.createElement('a');
            link.href = 'javascript:void(0)';

            // Truncate title to first 2 words + "..."
            let titleWords = workItemTitle.split(' ');
            let displayTitle = titleWords.length <= 2 ? workItemTitle : titleWords.slice(0, 2).join(' ') + '...';
            link.innerText = `${workItemId} ${displayTitle}`;

            // Prevent wrapping to second line
            link.style.whiteSpace = 'nowrap';
            link.style.overflow = 'hidden';
            link.style.textOverflow = 'ellipsis';
            link.style.display = 'block';
            link.style.textDecoration = 'underline';
            link.style.width = 'fit-content';
            if (isWeekOrDayView) link.style.color = 'white';

            link.addEventListener('click', function (e) {
                if (!isOrgLicenseValid) {
                    e.preventDefault();
                    return;
                }
                e.stopPropagation();
                OpenWorkItemDialog(workItemId);
            });

            container.appendChild(link);

            // Optional: Show time in non-list views
            // Calculate event duration (minutes)
            const isActive = arg.event.extendedProps.isActive;

            if (!arg.view.type.startsWith('list')) {
                let timeDiv = document.createElement('div');

                if (isActive) {
                    timeDiv.innerText = 'Active';
                    timeDiv.style.fontWeight = 'bold';
                } else {
                    const start = arg.event.start;
                    const end = arg.event.end;
                    const durationMinutes = (end - start) / (1000 * 60);

                    if (durationMinutes >= 30) {
                        timeDiv.innerText = `${formatHourWithAmPm(start)} - ${formatHourWithAmPm(end)}`;
                    }
                }
                timeDiv.style.fontSize = '0.85em';
                timeDiv.style.marginTop = '2px';
                if (isWeekOrDayView) timeDiv.style.color = 'white';
                container.appendChild(timeDiv);
            }

            // Add margin between multiple events in the same cell
            container.style.marginBottom = '2px';

            return { domNodes: [container] };
        },

        // Empty cell click → New timesheet
        dateClick: function (info) {
            if (!canLogTime) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Permission Denied',
                    text: 'You do not have permission to log time.',
                    confirmButtonColor: '#0078d4'
                });
                return;
            }
            if (!isOrgLicenseValid) return;

            const eventsAtTime = calendar.getEvents().filter(event => {
                const eventStart = new Date(event.start);
                const eventEnd = new Date(event.end);
                const clickTime = new Date(info.date);

                // Check if click time overlaps with any event
                return clickTime >= eventStart && clickTime <= eventEnd;
            });

            // If there are events at this time, don't open new timesheet panel
            if (eventsAtTime.length > 0) {
                return;
            }

            // Remove previous highlight before creating new one
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }

            // Create blue highlight to show user where they clicked
            tempHighlightEvent = calendar.addEvent({
                start: info.date,
                end: new Date(info.date.getTime() + 30 * 60 * 1000), // 30 minutes default
                display: 'background',
                backgroundColor: '#0078d4',
                borderColor: '#0078d4',
                classNames: ['temp-highlight-event'],
                title: 'highlight'
            });

            // Open panel for new timesheet
            if (typeof IndexLibrary.HandleTimeTrackingMenuOptionClick === 'function') {
                IndexLibrary.HandleTimeTrackingMenuOptionClick({
                    startDateTime: info.date,
                    timesheetTable: $("#timesheetsTable"),
                    totalLoggedHoursLabel: $("#workitem-page-logged-hours-button"),
                    apiUrl: baseAPIUrl,
                    azureAuthenticationHeader: azureAuthenticationHeader,
                    EditWorkItem: true,
                    onClose: () => {
                        // Remove highlight when panel closes
                        if (tempHighlightEvent) {
                            tempHighlightEvent.remove();
                            tempHighlightEvent = null;
                        }
                    }
                });
            } else {
                console.error("IndexLibrary.HandleTimeTrackingMenuOptionClick is not a function");
                // Remove highlight if panel can't open
                if (tempHighlightEvent) {
                    tempHighlightEvent.remove();
                    tempHighlightEvent = null;
                }
            }
        },

        // Event click → Edit existing timesheet
        eventClick: async function (info) {
            if (!isOrgLicenseValid) return;

            // Prevent opening panel for highlight events
            if (info.event.extendedProps.title === 'highlight') {
                return;
            }

            // Remove previous highlight before creating new one
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }

            // Create blue highlight around the clicked event
            tempHighlightEvent = calendar.addEvent({
                start: info.event.start,
                end: info.event.end,
                display: 'background',
                backgroundColor: '#0078d4',
                borderColor: '#0078d4',
                classNames: ['temp-highlight-event'],
                title: 'highlight'
            });

            const eventData = info.event.extendedProps;

            // Build action context
            const actionContext = {
                startDateTime: info.event.start,
                timesheetTable: $("#timesheetsTable"),
                totalLoggedHoursLabel: $("#workitem-page-logged-hours-button"),
                apiUrl: baseAPIUrl,
                azureAuthenticationHeader: azureAuthenticationHeader,
                EditWorkItem: true,
                timesheetId: eventData.timesheetId,
                workItemId: eventData.workItemId,
                workItemTitle: eventData.workItemTitle,
                workStarted: info.event.start.toISOString(),
                workEnded: info.event.end ? info.event.end.toISOString() : null,
                trackingWorkItemTypeId: eventData.workTypeId,
                description: eventData.workDescription,
                isBillable: eventData.isBillable,
                organizationName: organizationName
            };


            // Open panel for editing
            if (typeof IndexLibrary.HandleEditLoggedTimeClick === 'function') {
                IndexLibrary.HandleEditLoggedTimeClick({
                    ...actionContext,
                    onClose: () => {
                        // Remove highlight when panel closes
                        if (tempHighlightEvent) {
                            tempHighlightEvent.remove();
                            tempHighlightEvent = null;
                        }
                    }
                });
            } else {
                console.error("IndexLibrary.HandleEditLoggedTimeClick is not a function");
                // Remove highlight if panel can't open
                if (tempHighlightEvent) {
                    tempHighlightEvent.remove();
                    tempHighlightEvent = null;
                }
            }
        },

        // Remove highlights when calendar view changes
        datesSet: function (dateInfo) {
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }
        },

        eventDrop: function (info) {
            // Remove highlight if it exists
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }

            Swal.fire({
                title: '',
                text: "Confirm timesheet change ?",
                icon: '',
                showCancelButton: true,
                confirmButtonColor: '#0078d4',
                cancelButtonColor: '#8f8f8f',
                confirmButtonText: 'Yes',
                cancelButtonText: 'No'
            }).then((result) => {
                if (result.isConfirmed) {
                    UpdateTimesheet(info);
                } else {
                    info.revert();
                }
            });

        },
        eventResize: function (info) {
            // Remove highlight if it exists
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }

            Swal.fire({
                title: '',
                text: "Confirm timesheet change ?",
                icon: '',
                showCancelButton: true,
                confirmButtonColor: '#0078d4',
                cancelButtonColor: '#8f8f8f',
                confirmButtonText: 'Yes',
                cancelButtonText: 'No'
            }).then((result) => {
                if (result.isConfirmed) {
                    UpdateTimesheet(info);
                } else {
                    info.revert();
                }
            });
        },

        dayCellDidMount: function (dayCellData) {
            var element = document.createElement('div');
            var className = 'totalHours-' + new Date(dayCellData.date).toLocaleDateString('en-GB').replaceAll('/', '-')
            element.classList.add(className);
            element.style.position = 'absolute';
            element.style.bottom = '0';
            element.style.left = '0';
            element.appendChild(document.createTextNode('Total Hours: 0'));
            dayCellData.el.childNodes[0].appendChild(element);
        },
        eventDidMount: function (data) {
            // Skip styling for our temporary highlight events
            if (data.event.title === 'highlight' || data.event.extendedProps.title === 'highlight') {
                // Apply specific styling for highlight events
                data.el.style.opacity = '0.3';
                data.el.style.pointerEvents = 'none';
                data.el.style.zIndex = '1';
                return;
            }
            if (data.event.extendedProps.isActive) {
                data.el.style.opacity = '0.85';
                data.el.style.cursor = 'not-allowed';
                data.el.classList.add('active-timesheet');
            }

            const workTypeId = data.event.extendedProps.workTypeId;
            const eventColor = GetWorkTypeColor(workTypeId);
            // Calculate THIS event duration only
            const start = data.event.start;
            const end = data.event.end;

            let eventHours = 0;
            if (start && end) {
                eventHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
            }

            if (data.view.type === "dayGridMonth" || data.view.type === "timeGridWeek" || data.view.type === "timeGridDay") {
                // Day/Week/Month view → full blue background + left colored bar
                const fullBlue = '#0078d4';
                data.el.style.backgroundColor = fullBlue;
                data.el.style.color = '#fff';
                data.el.style.borderRadius = '4px';
                data.el.style.paddingLeft = '6px';
                data.el.style.borderLeft = `4px solid ${eventColor}`;
                data.el.style.borderRight = '1px solid #005a9e'; // optional subtle right border
            } else if (data.view.type.startsWith('list')) {
                // List view → only dot color changes, keep everything else default
                const dot = data.el.querySelector('.fc-list-event-dot');
                if (dot) {
                    dot.style.backgroundColor = eventColor;
                    dot.style.borderColor = eventColor;
                }
            }
            var tooltipHtml =
                "<div>" +
                "<b>Timesheet Entry</b><br />" +
                "<span>Total Hours: " + eventHours.toFixed(2) + "</span><br />" +
                "<span>Work Type: " + data.event.extendedProps.workType + "</span><br />" +
                "<span>Description: " + data.event.extendedProps.workDescription + "</span><br />" +
                "<span>Billable: " + (data.event.extendedProps.isBillable ? "Yes" : "No") + "</span>" +
                "</div>";
            if (data.view.type == "dayGridMonth" || data.view.type == "timeGridWeek" || data.view.type == "timeGridDay") {
                var totalHoursDiv = document.getElementsByClassName(data.event.extendedProps.headerClass)[0];
                if (totalHoursDiv) {
                    const eventsForDay = calendar.getEvents().filter(ev => ev.extendedProps.headerClass === data.event.extendedProps.headerClass && ev.title !== 'highlight');
                    let totalHours = 0;
                    eventsForDay.forEach(ev => {
                        totalHours += parseFloat(ev.extendedProps.hours || 0);
                    });
                    totalHoursDiv.innerText = 'Total Hours: ' + totalHours.toFixed(2);
                }
                $(data.el).qtip({
                    content: { text: tooltipHtml },
                    position: {
                        my: 'bottom center',
                        at: 'top center'
                    }
                });
            }
            else if (data.view.type.startsWith("list")) {

                $(data.el)
                    .closest('tr.fc-list-event')
                    .qtip({
                        content: { text: tooltipHtml },
                        position: {
                            my: 'bottom center',
                            at: 'top center'
                        }
                    });
            }
        }
    });
    calendar.render();

    setButtonState('.fc-logTime-button', isOrgLicenseValid);

    addCustomMoreButton();

    calendar.on('datesSet', function () {
        const oldWrapper = document.querySelector('.custom-moreOptions-wrapper');
        if (oldWrapper) oldWrapper.remove();
        addCustomMoreButton();
    });


    // Add click handler to remove highlight when clicking elsewhere
    document.addEventListener('click', function (event) {

        const isCalendarNav = event.target.closest('.fc-toolbar-chunk') !== null;
        const isCalendarCell = event.target.closest('.fc-timegrid-slot, .fc-daygrid-day-frame') !== null;
        const isModal = event.target.closest('.swal2-container, .modal, .panel') !== null;

        // If clicking navigation buttons (not cells), remove highlight
        if (isCalendarNav && !isCalendarCell && !isModal) {
            if (tempHighlightEvent) {
                tempHighlightEvent.remove();
                tempHighlightEvent = null;
            }
        }
    });

    return calendar;
}
function addCustomMoreButton() {
    const moreBtn = document.querySelector('.fc-moreOptions-button');

    if (!moreBtn) return;
    if (moreBtn.closest('.custom-moreOptions-wrapper')) return;

    const spanWrapper = document.createElement('span');
    spanWrapper.classList.add('custom-moreOptions-wrapper');
    spanWrapper.style.display = 'inline-block';
    spanWrapper.style.marginLeft = '4px';
    spanWrapper.innerHTML = `
        <div class="dropdown d-inline-block m-0">
            <button class="btn p-0 border-0 bg-transparent shadow-none"
                    type="button"
                    data-bs-toggle="dropdown"
                    style="line-height:1; display:inline-flex; align-items:center;">
                <i class="bi bi-three-dots-vertical fs-5"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end shadow">
               
                    <a class="dropdown-item" href="#" onclick="openUserHelpLink()">
                       <i class="fa-solid fa-circle-question text-muted"></i>
                        Help Link
                    </a>
                </li>
                <li>
                    <a class="dropdown-item" href="#" onclick="openUserGuideLink()">
                        <i class="fa-solid fa-book text-muted"></i>
                        User Guide
                    </a>
                </li>
            </ul>
        </div>
    `;
    moreBtn.replaceWith(spanWrapper);
}

function GetWorkTypeColor(workTypeId) {
    const item = WorkTypeColor.find(w => w.id === workTypeId);
    return item ? item.color : '#0078d4';
}

function formatHourWithAmPm(date) {
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let period = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    if (hours === 0) hours = 12;
    minutes = minutes.toString().padStart(2, '0');
    return `${hours}:${minutes} ${period}`;
}
async function OpenWorkItemDialog(workItemId) {
    var currentProjectName = await IndexLibrary.GetCurrentProjectName();
    var workItemUrl = "https://dev.azure.com/" + organizationName + "/" + currentProjectName + "/_workitems/edit/" + workItemId + "/";
    window.open(workItemUrl, '_blank');

}
window.addEventListener('message', (event) => {
    if (localStorage.getItem("timeSheetChanged") === "true") {
        localStorage.removeItem("timeSheetChanged");
        GetProjectTimesheetsByUserEmail();
    }
});

async function LoadWorkTypeColors() {

    if (WorkTypeColor.length > 0) return;

    try {
        const response = await IndexLibrary.GetRequest({
            endpoint: `/api/TrackingWorkType/GetAll/${organizationName}`
        });

        const data = await response.json();


        WorkTypeColor = data.map(t => ({
            id: t.id,
            title: t.trackingWorkTypeTitle,
            color: t.trackingWorkTypeColor
        }));


    } catch (error) {
        console.error("❌ Failed to load work type colors", error);
    }
}

async function applyLogTimePermission() {
    const licensedUserType = await IndexLibrary.GetUserLicensesType(fieldName, true);

    canLogTime = !!licensedUserType;

    const logTimeBtn = document.querySelector('.fc-logTime-button');
    if (logTimeBtn) {
        logTimeBtn.style.display = canLogTime ? "inline-block" : "none";
    }
}
function openUserGuideLink() {
    IndexLibrary.openInNewTab(userguidelink);
}

function openUserHelpLink() {
    IndexLibrary.openInNewTab(userhelplink);
}