import React, { useState, useEffect, useRef, memo, useCallback, useMemo } from 'react';
import { makeStyles, Typography, useTheme, Fade, lighten, Button } from '@material-ui/core';
import { IconRenderer } from '../../../UI/templates/ui/renderers/IconRenderer';
import { TimelineNode } from '../ui/TimelineNode';
import { TimelineWrapper } from '../ui/TimelineWrapper';
import { MultiDot } from '../ui/MultiDot';
import { VisualizationDot } from '../ui/VisualizationDot';
import { TimelinePreloaderNode } from '../ui/TimelinePreloaderNode';
import 'react-range-slider-input/dist/style.css';
import { MttYearTag } from '../ui/MttYearTag';
import { DynamicRangeSlider } from '../ui/DynamicRangeSlider';
import { HeightAdjuster } from './HeightAdjust';
const useStyles = makeStyles((theme) => ({
    root: {},
    horizontalDash: {
        backgroundImage: 'linear-gradient(to right, grey 33%, rgba(255,255,255,0) 0%)',
        backgroundPosition: 'bottom',
        backgroundSize: '16px 1px',
        backgroundRepeat: 'repeat-x'
    },
    slider: {
        height: 600
    },
    categoryBar: {
        background: lighten(theme.palette.common.black, 0.5),
        color: theme.palette.common.white,
        display: 'flex',
        alignItems: 'center'
    },
    categoryBarPlacement: {
        position: 'absolute',
        left: 0
    },
    categoryLabel: {
        transform: 'rotate(90deg)',
        width: 28
    },
    button: {
        '&:hover': {
            textDecoration: 'line-through'
        }
    }
}));
// eslint-disable-next-line react/display-name
export const MttTimeline = memo((props) => {
    var _a;
    const [showAllDetails] = useState(false);
    const [startRange, setStartRange] = useState(10);
    const [endRange, setEndRange] = useState();
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [displayRangeFilter, setDisplayRangeFilter] = useState(true);
    const [threadHeight, setThreadHeight] = useState(92);
    const [recordLength, setRecordLength] = useState();
    const [containerWidth, setContainerWidth] = useState();
    const [showMonthMarkers, setShowMonthMarkers] = useState(false);
    const [showYearMarkers, setShowYearMarkers] = useState(false);
    const [verticalAdjuster, setVerticalAdjuster] = useState(4.5);
    const [uniqueTimelines, setUniqueTimelines] = useState(0);
    const classes = useStyles(props);
    const { data, loading } = props;
    const theme = useTheme();
    const visualizationYScale = 40;
    useEffect(() => {
        const years = [];
        data &&
            data.map((item) => {
                years.push(item.date.slice(-4));
            });
        //unique years
        const uniqueYears = [...new Set(years)].sort();
        data && setStartDate(uniqueYears[0] + '-01-01');
        data && setEndDate(uniqueYears[uniqueYears.length - 1] + '-12-31');
    }, [data]);
    const mainContainer = useRef(null);
    useEffect(() => {
        setContainerWidth(mainContainer.current ? mainContainer.current.offsetWidth : 0);
    }, []);
    let movement_timer = null;
    const RESET_TIMEOUT = 10;
    const set_dimensions = () => {
        if (mainContainer.current) {
            setContainerWidth(mainContainer.current.offsetWidth);
        }
    };
    window.addEventListener('resize', () => {
        clearInterval(movement_timer);
        movement_timer = setTimeout(set_dimensions, RESET_TIMEOUT);
    });
    const years = [];
    data &&
        data.map((item) => {
            years.push(item.date.slice(-4));
        });
    //unique years
    const uniqueYears = [...new Set(years)];
    let demoApiConfigDate = [];
    uniqueYears.map((item) => {
        demoApiConfigDate.push('01/01/' + item);
    });
    let yearsInRange = [];
    yearsInRange.push(Number((_a = demoApiConfigDate[1]) === null || _a === void 0 ? void 0 : _a.slice(-4)) + 1);
    let yearsToDisplay = [];
    yearsInRange.map((item) => {
        yearsToDisplay.push('01/01/' + item);
    });
    demoApiConfigDate.map((item) => {
        yearsToDisplay.unshift(item);
    });
    const yearRange = yearsToDisplay.sort();
    // could change plotting on range change by switching data with filteredByDate
    const getSingleGroupedData = useCallback(() => {
        const flatOne = data && data.map((item) => item.dates).flat();
        const flatTwo = data &&
            flatOne &&
            flatOne.map((item) => {
                return item.details;
            });
        return flatTwo;
    }, [data]);
    // Sort date
    const sortDate = data &&
        getSingleGroupedData().sort(function (a, b) {
            const c = new Date(a.date);
            const d = new Date(b.date);
            return c - d;
        });
    // Convert date format
    let dataConvertedDate = data &&
        sortDate.map((item) => (Object.assign(Object.assign({}, item), { date: new Date(item.date).toLocaleDateString() })));
    function formatDate(date) {
        return new Date(date).toLocaleDateString('en-US');
    }
    const getPositionFromDate = useCallback((initDate) => {
        const start = new Date(yearRange[1]);
        const end = new Date(yearRange[2]);
        const rangeStart = [initDate];
        const dateList = [new Date(start).toLocaleDateString()];
        let loop = new Date(start);
        while (loop <= end) {
            const newDate = loop.setDate(loop.getDate() + 1);
            loop = new Date(newDate);
            dateList.push(loop.toLocaleDateString());
        }
        const mappedToObjects = dateList.map(function (value) {
            return { date: value };
        });
        const plots = [];
        for (let i = 1; i <= dateList.length; i++) {
            plots.push(i);
        }
        let mergePlots = mappedToObjects.map((o, i) => (Object.assign(Object.assign({}, o), { plots: plots[i] || null })));
        const startDate = mergePlots
            .filter(({ date }) => rangeStart.includes(date))
            .map(({ plots }) => plots)
            .toString();
        return startDate;
    }, [yearRange]);
    let demoDates = [];
    dataConvertedDate &&
        dataConvertedDate.map((item) => {
            demoDates.push(item.date);
        });
    let unique = [...new Set(demoDates)];
    useEffect(() => {
        setEndRange(unique && Number(getPositionFromDate(unique.slice(-1).pop())) + 66);
    }, []);
    const getDatesFromRangeSelectionCompact = useCallback((left, right) => {
        const rangeStart = [Math.round(left)];
        const rangeEnd = [Math.round(right)];
        let demoDates = [];
        dataConvertedDate &&
            dataConvertedDate.map((item) => {
                demoDates.push(item.date);
            });
        let unique = [...new Set(demoDates)];
        const getNextDay = () => {
            const dateString = unique[unique.length - 1];
            const date = new Date(dateString);
            date.setDate(date.getDate() + 1);
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const year = date.getFullYear();
            return `${month}/${day}/${year}`;
        };
        const nextDay = getNextDay();
        unique.push(nextDay);
        const mappedToObjects = unique.map(function (value) {
            return { date: value };
        });
        const plots = [];
        for (let i = 1; i <= unique.length; i++) {
            plots.push(i * 10);
        }
        let mergePlots = mappedToObjects.map((o, i) => (Object.assign(Object.assign({}, o), { plots: plots[i] || null })));
        const startDate = mergePlots
            .filter(({ plots }) => rangeStart.includes(plots))
            .map(({ date }) => date)
            .toString();
        const endDate = mergePlots
            .filter(({ plots }) => rangeEnd.includes(plots))
            .map(({ date }) => date)
            .toString();
        setStartDate(startDate);
        setEndDate(endDate);
    }, [dataConvertedDate]);
    const getRangeValues = useCallback((rangeValue) => {
        const left = rangeValue[0];
        const right = rangeValue[1];
        setStartRange(Math.round(left));
        setEndRange(Math.round(right));
    }, []);
    const processRangeValues = () => {
        endRange && getDatesFromRangeSelectionCompact(startRange, endRange);
    };
    // Plot YV
    const plotYV = useCallback((item) => {
        const plotDate = [item];
        let demoDates = [];
        dataConvertedDate &&
            dataConvertedDate.map((item) => {
                demoDates.push(item.date);
            });
        let demoDatesTwo = [];
        data &&
            data.map((item) => {
                demoDatesTwo.push(item.date);
            });
        let unique = [...new Set(demoDatesTwo)];
        let results = unique.map((date) => new Date(date));
        const resultsSorted = results.sort((a, b) => a.getTime() - b.getTime());
        const dtest = resultsSorted.map((date) => date.toLocaleDateString());
        const mappedToObjects = dtest.map(function (value) {
            return { date: value };
        });
        const plots = [];
        for (let i = 1; i <= unique.length; i++) {
            plots.push(i);
        }
        let mergePlots = mappedToObjects.map((o, i) => (Object.assign(Object.assign({}, o), { plots: plots[i] || null })));
        const res = mergePlots
            .filter(({ date }) => plotDate.includes(date))
            .map(({ plots }) => plots);
        const order = res.map((item) => {
            return item;
        });
        const plot = order;
        return plot;
    }, [data, dataConvertedDate]);
    function compareDate(date1, date2, comparison) {
        const date1Month = Number(date1.split('/')[0]);
        const date2Month = Number(date2.split('/')[0]);
        const date1Day = Number(date1.split('/')[1]);
        const date2Day = Number(date2.split('/')[1]);
        const date1Year = Number(date1.split('/')[2]);
        const date2Year = Number(date2.split('/')[2]);
        if (comparison === '>') {
            if (date1Year > date2Year) {
                return true;
            }
            else if (date1Year === date2Year) {
                if (date1Month > date2Month) {
                    return true;
                }
                else if (date1Month === date2Month) {
                    if (date1Day > date2Day) {
                        return true;
                    }
                }
            }
            return false;
        }
        else {
            if (date1Year < date2Year) {
                return true;
            }
            else if (date1Year === date2Year) {
                if (date1Month < date2Month) {
                    return true;
                }
                else if (date1Month === date2Month) {
                    if (date1Day < date2Day) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
    function minnifyTimelineObject(object) {
        let cleanObject = [];
        let notUsed = false;
        object.forEach((obj, i) => {
            if (cleanObject.length === 0) {
                cleanObject.push({
                    timeline: obj.timeline,
                    subThread: obj.subThread,
                    firstDate: formatDate(obj.date),
                    lastDate: formatDate(obj.date),
                    color: obj.color,
                    icon: obj.iconID
                });
            }
            else {
                notUsed = true;
                cleanObject.forEach((clnObj) => {
                    if (obj.timeline === clnObj.timeline &&
                        obj.subThread === clnObj.subThread) {
                        if (compareDate(formatDate(obj.date), formatDate(clnObj.firstDate), '<')) {
                            clnObj.firstDate = formatDate(obj.date);
                        }
                        else if (compareDate(formatDate(obj.date), formatDate(clnObj.lastDate), '>')) {
                            clnObj.lastDate = formatDate(obj.date);
                        }
                        notUsed = false;
                    }
                });
            }
            if (notUsed) {
                cleanObject.push({
                    timeline: obj.timeline,
                    subThread: obj.subThread,
                    firstDate: formatDate(obj.date),
                    lastDate: formatDate(obj.date),
                    color: obj.color,
                    icon: obj.iconID
                });
            }
        });
        return cleanObject;
    }
    let dates = [];
    dataConvertedDate &&
        dataConvertedDate.map((item) => {
            dates.push(item.date);
        });
    const plots = [];
    for (let i = 1; i <= unique.length; i++) {
        plots.push(i);
    }
    const startDateSet = useMemo(() => new Date(startDate), [startDate]);
    const endDateSet = useMemo(() => new Date(endDate), [endDate]);
    const filteredByDate = data &&
        data.filter((item) => {
            const date = new Date(item.date);
            return date >= startDateSet && date < endDateSet;
        });
    const buildCategoryLines = useCallback(() => {
        const xLine = data &&
            (filteredByDate === null || filteredByDate === void 0 ? void 0 : filteredByDate.map((item) => {
                return item.timeline.toString() + '.' + item.subThread.toString();
            }));
        let unique = [...new Set(xLine)];
        return unique;
    }, [filteredByDate, data]);
    const minnifiedResult = data && minnifyTimelineObject(filteredByDate);
    const detailedComponentSize = 130;
    const summaryComponentSize = 73;
    //const overviewComponentSize = 50;
    //const detailBreakpoint = Math.round(containerWidth / detailedComponentSize);
    const summaryBreakpoint = Math.round(containerWidth / detailedComponentSize);
    const overviewBreakpoint = Math.round(containerWidth / summaryComponentSize);
    useEffect(() => {
        const filteredByDate = data &&
            data.filter((item) => {
                const date = new Date(item.date);
                return date >= startDateSet && date <= endDateSet;
            });
        setRecordLength(filteredByDate === null || filteredByDate === void 0 ? void 0 : filteredByDate.length);
    }, [data, endDateSet, startDateSet]);
    const checkLinearLength = [];
    filteredByDate === null || filteredByDate === void 0 ? void 0 : filteredByDate.forEach((item) => {
        checkLinearLength.push(item.date);
    });
    let uniqueNodeScaleAmount = [...new Set(checkLinearLength)].length;
    const getScale = useCallback(() => {
        if (uniqueNodeScaleAmount > overviewBreakpoint) {
            return 50;
        }
        else if (uniqueNodeScaleAmount >= summaryBreakpoint) {
            return summaryComponentSize;
        }
        else {
            return 186;
        }
    }, [uniqueNodeScaleAmount, summaryBreakpoint, overviewBreakpoint]);
    const getXScale = useCallback(() => {
        if (uniqueNodeScaleAmount > overviewBreakpoint) {
            return 50;
        }
        else if (uniqueNodeScaleAmount >= summaryBreakpoint) {
            return summaryComponentSize;
        }
        else {
            return 186;
        }
    }, [uniqueNodeScaleAmount, summaryBreakpoint, overviewBreakpoint]);
    const getYScale = useCallback(() => {
        if (uniqueNodeScaleAmount > overviewBreakpoint) {
            return 50;
        }
        else if (uniqueNodeScaleAmount >= summaryBreakpoint) {
            return summaryComponentSize;
        }
        else {
            return 130;
        }
    }, [uniqueNodeScaleAmount, summaryBreakpoint, overviewBreakpoint]);
    const topMargin = uniqueNodeScaleAmount >= summaryBreakpoint ? 48 : 0;
    // Plot XV
    const plotXV = useCallback((timeline, subThread) => {
        const xLine = data &&
            data.map((item) => {
                return item.timeline + '.' + item.subThread;
            });
        let unique = [...new Set(xLine)];
        const rowIndex = unique.reduce(function (s, a) {
            s.push({ thread: a });
            return s;
        }, []);
        const sortedRowIndex = rowIndex.sort((a, b) => a.thread > b.thread ? 1 : -1);
        const concatIndex = timeline + '.' + subThread;
        const result = sortedRowIndex.map((v, index) => (Object.assign(Object.assign({}, v), { sortedRowIndex: index })));
        const results = result.filter(function (entry) {
            return entry.thread === concatIndex;
        });
        const xplot = results[0] && results[0].sortedRowIndex * 50;
        return xplot - topMargin;
    }, [data, topMargin]);
    const plotY = useCallback((item) => {
        const plotDate = [item];
        let demoDates = [];
        dataConvertedDate &&
            dataConvertedDate.map((item) => {
                demoDates.push(item.date);
            });
        let demoDatesTwo = [];
        dataConvertedDate &&
            filteredByDate.map((item) => {
                demoDatesTwo.push(item.date);
            });
        let unique = [...new Set(demoDatesTwo)];
        let results = unique.map((date) => new Date(date));
        const resultsSorted = results.sort((a, b) => a.getTime() - b.getTime());
        const dtest = resultsSorted.map((date) => date.toLocaleDateString());
        const mappedToObjects = dtest.map(function (value) {
            return { date: value };
        });
        const plots = [];
        for (let i = 1; i <= unique.length; i++) {
            plots.push(i);
        }
        let mergePlots = mappedToObjects.map((o, i) => (Object.assign(Object.assign({}, o), { plots: plots[i] || null })));
        const res = mergePlots &&
            mergePlots
                .filter(({ date }) => plotDate.includes(date))
                .map(({ plots }) => plots);
        const order = mergePlots &&
            res.map((item) => {
                return item;
            });
        const plot = order * getYScale();
        return plot - getYScale() + (getYScale() === 130 ? 32 : 8);
    }, [dataConvertedDate, getYScale, filteredByDate]);
    const plotX = useCallback((timeline, subThread) => {
        const xLine = data &&
            filteredByDate.map((item) => {
                return item.timeline + '.' + item.subThread;
            });
        let unique = [...new Set(xLine)];
        const rowIndex = unique.reduce(function (s, a) {
            s.push({ thread: a });
            return s;
        }, []);
        // const sortedRowIndex = rowIndex.sort((a, b) =>
        //   a.thread > b.thread ? 1 : -1
        // );
        const orderByThread = (unordered) => {
            let maxElement = 0;
            unordered.forEach((value) => {
                if (value.thread.split('.')[0] > maxElement) {
                    maxElement = value.thread.split('.')[0];
                }
            });
            let sortArray = [...Array(+maxElement)].map((e) => (e = []));
            unordered.forEach((value) => {
                sortArray[+value.thread.split('.')[0] - 1].push(value);
            });
            sortArray.forEach((value) => {
                value.sort((a, b) => {
                    return +a.thread.split('.')[1] - +b.thread.split('.')[1];
                });
            });
            return sortArray.flat();
        };
        const sortedRowIndex = orderByThread(rowIndex);
        const concatIndex = timeline + '.' + subThread;
        const result = sortedRowIndex.map((v, index) => (Object.assign(Object.assign({}, v), { sortedRowIndex: index })));
        const results = result.filter(function (entry) {
            return entry.thread === concatIndex;
        });
        const xplot = results[0] && results[0].sortedRowIndex * getXScale();
        return xplot + topMargin;
    }, [data, getXScale, topMargin, filteredByDate]);
    // Map to named months
    const MONTHS = {
        1: 'Jan',
        2: 'Feb',
        3: 'March',
        4: 'Apr',
        5: 'May',
        6: 'June',
        7: 'July',
        8: 'Aug',
        9: 'Sept',
        10: 'Oct',
        11: 'Nov',
        12: 'Dec'
    };
    const convertNumberToMonths = (months) => {
        // Convert months to order
        const orderedMonths = months;
        orderedMonths.sort(function (a, b) {
            return a - b;
        });
        // Map to named months
        const output = orderedMonths.map(function (i) {
            return MONTHS[i];
        });
        return output;
    };
    function lastDayOfMonthArray(object) {
        let tempDates = [];
        let dates = [];
        object.forEach((obj) => {
            if (!tempDates.find((date) => date === formatDate(obj.date))) {
                tempDates.push(formatDate(obj.date));
            }
        });
        tempDates.forEach((date) => {
            const dateMonth = Number(date.split('/')[0]);
            const dateYear = Number(date.split('/')[2]);
            let pushDate = '12/31/9999';
            tempDates.forEach((fDate) => {
                const fDateMonth = Number(fDate.split('/')[0]);
                const fDateDay = Number(fDate.split('/')[1]);
                const fDateYear = Number(fDate.split('/')[2]);
                if (fDateYear === dateYear &&
                    fDateMonth === dateMonth &&
                    fDateDay < Number(pushDate.split('/')[1])) {
                    pushDate = fDate;
                }
            });
            if (pushDate !== '12/31/9999') {
                dates.push(pushDate);
            }
        });
        dates = [...new Set(dates)];
        const returnObject = dates.map((date) => {
            let timelines = [];
            let subThreads = [];
            object.forEach((obj) => {
                if (formatDate(obj.date) === formatDate(date)) {
                    timelines.push(obj.timeline);
                    subThreads.push(obj.subThread);
                }
            });
            return {
                date: date,
                timelines: timelines,
                subThread: subThreads
            };
        });
        return returnObject;
    }
    useEffect(() => {
        const timelineSet = new Set();
        data &&
            data.forEach((item) => {
                const timelineKey = `${item.timeline}-${item.subThread}`;
                timelineSet.add(timelineKey);
            });
        setUniqueTimelines(timelineSet.size);
    }, [data]);
    function lastDayOfYearArray(object) {
        let tempDates = [];
        let dates = [];
        object.forEach((obj) => {
            if (!tempDates.find((date) => date === formatDate(obj.date))) {
                tempDates.push(formatDate(obj.date));
            }
        });
        tempDates.forEach((date) => {
            const dateMonth = Number(date.split('/')[0]);
            const dateYear = Number(date.split('/')[2]);
            let pushDate = '00/00/00';
            tempDates.forEach((fDate) => {
                const fDateMonth = Number(fDate.split('/')[0]);
                const fDateDay = Number(fDate.split('/')[1]);
                const fDateYear = Number(fDate.split('/')[2]);
                if (fDateYear === dateYear &&
                    fDateMonth === dateMonth &&
                    fDateDay > Number(pushDate.split('/')[1])) {
                    pushDate = fDate;
                }
            });
            if (pushDate !== '00/00/00') {
                dates.push(pushDate);
            }
        });
        dates = [...new Set(dates)];
        dates.sort((a, b) => new Date(a) - new Date(b));
        let dateArr = [];
        for (let x = 0; x < dates.length; x++) {
            if (x === dates.length - 1 ||
                Number(dates[x].split('/')[2]) !== Number(dates[x + 1].split('/')[2])) {
                dateArr.push(dates[x]);
            }
        }
        const returnObject = dateArr.map((date) => {
            let timelines = [];
            let subThreads = [];
            object.forEach((obj) => {
                if (formatDate(obj.date) === formatDate(date)) {
                    timelines.push(obj.timeline);
                    subThreads.push(obj.subThread);
                }
            });
            return {
                date: date,
                timelines: timelines,
                subThread: subThreads
            };
        });
        return returnObject;
    }
    function firstDayOfYearArray(object) {
        let tempDates = [];
        let dates = [];
        object.forEach((obj) => {
            if (!tempDates.find((date) => date === formatDate(obj.date))) {
                tempDates.push(formatDate(obj.date));
            }
        });
        tempDates.forEach((date) => {
            const dateMonth = Number(date.split('/')[0]);
            const dateYear = Number(date.split('/')[2]);
            let pushDate = '12/31/9999';
            tempDates.forEach((fDate) => {
                const fDateMonth = Number(fDate.split('/')[0]);
                const fDateDay = Number(fDate.split('/')[1]);
                const fDateYear = Number(fDate.split('/')[2]);
                if (fDateYear === dateYear &&
                    fDateMonth === dateMonth &&
                    fDateDay < Number(pushDate.split('/')[1])) {
                    pushDate = fDate;
                }
            });
            if (pushDate !== '12/31/9999') {
                dates.push(pushDate);
            }
        });
        dates = [...new Set(dates)];
        dates.sort((a, b) => new Date(b) - new Date(a));
        let dateArr = [];
        for (let x = 0; x < dates.length; x++) {
            if (x === dates.length - 1 ||
                Number(dates[x].split('/')[2]) !== Number(dates[x + 1].split('/')[2])) {
                dateArr.push(dates[x]);
            }
        }
        dateArr.sort((a, b) => new Date(a) - new Date(b));
        const returnObject = dateArr.map((date) => {
            let timelines = [];
            let subThreads = [];
            object.forEach((obj) => {
                if (formatDate(obj.date) === formatDate(date)) {
                    timelines.push(obj.timeline);
                    subThreads.push(obj.subThread);
                }
            });
            return {
                date: date,
                timelines: timelines,
                subThread: subThreads
            };
        });
        return returnObject;
    }
    const Today = (object) => {
        const dateList = [];
        object &&
            object.map((item) => {
                dateList.push(item.date);
            });
        let unique = [...new Set(dateList)];
        const today = new Date().toLocaleDateString('en-US');
        //const todaysDate = unique.filter(date => date.includes('7/29/2022'));
        const todaysDate = unique.filter((date) => date.includes(today));
        return todaysDate;
    };
    const getInverseProportionalNumber = (inputNumber) => {
        const reciprocal = 1 / inputNumber;
        const wholeNumber = Math.round(reciprocal * 400);
        return wholeNumber;
    };
    const visualizationSmall = 10;
    const visualizationLarge = 30;
    const rangeHandles = 18;
    const adjusterHeight = 100;
    // Plot category lines
    const GuideLinesShort = () => {
        const xLines = buildCategoryLines().map((item, index) => {
            return (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    zIndex: 0,
                    top: 186 * index
                } }, React.createElement("div", { className: classes.horizontalDash, style: { height: threadHeight } }), React.createElement("div", { style: {
                    //width: 'calc(100vw * 1.7)',
                    width: 
                    // dataConvertedDate &&
                    // mergePlots.slice(-1).pop().plots * nodeWidth,
                    filteredByDate &&
                        uniqueNodeScaleAmount * getXScale() + getXScale(),
                    height: threadHeight,
                    borderBottom: `${theme.palette.divider} 1px solid`
                } })));
        });
        return xLines;
    };
    const preloadArray = [...Array(7).keys()];
    //Format visualization hover card
    const VisualizationCard = ({ title, data, date, user }) => {
        return (React.createElement("div", null, React.createElement(Typography, { variant: "subtitle2" }, " ", title, " "), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", data, " ")), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", date, " ")), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", user, " "))));
    };
    const VisualizationCardMulti = ({ title, data, date, user }) => {
        return (React.createElement("div", { style: {
                width: 130,
                borderRadius: 4,
                marginBottom: 16,
                padding: 8
            } }, React.createElement("div", null, React.createElement(Typography, { variant: "subtitle2" }, " ", title, " ")), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", data, " ")), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", date, " ")), React.createElement("div", null, React.createElement(Typography, { variant: "caption" }, " ", user, " "))));
    };
    // Plot Legend
    const categoryList = [];
    data &&
        filteredByDate.map((item) => {
            categoryList.push({
                label: item.timelineCategoryName,
                color: item.color,
                timeline: item.timeline
            });
        });
    const uniqueCategoryLegend = [
        ...new Map(categoryList.map((item) => [item['label'], item])).values()
    ];
    const uniqueCategoryLegendSorted = uniqueCategoryLegend.sort((a, b) => a.timeline > b.timeline ? 1 : -1);
    const LegendDot = ({ background }) => {
        return (React.createElement("div", { style: {
                width: 30,
                height: 15,
                background: lighten(background, 0.5),
                borderRadius: theme.spacing(6)
            } }));
    };
    const LegendItem = ({ label, color }) => {
        return (React.createElement("div", { style: {
                display: 'flex',
                alignItems: 'center'
            } }, React.createElement(LegendDot, { background: '#' + color }), React.createElement("div", { style: { marginLeft: theme.spacing(1) } }, React.createElement(Typography, { variant: "caption" }, label, " "))));
    };
    const legend = data &&
        uniqueCategoryLegendSorted.map((item, index) => {
            return React.createElement(LegendItem, { key: index, color: item.color, label: item.label });
        });
    // Plot category bar
    const plotCategoryBar = (timelineNumber, subThread) => {
        const xLine = data &&
            filteredByDate.map((item) => {
                return item.timeline.toString() + '.' + item.subThread.toString();
            });
        let unique = [...new Set(xLine)];
        const uniqueSorted = unique.sort(function (a, b) {
            return a.localeCompare(b);
        });
        const rowIndex = uniqueSorted.reduce(function (s, a) {
            s.push({ thread: a });
            return s;
        }, []);
        const concatIndex = timelineNumber + '.' + subThread;
        const result = rowIndex.map((v, index) => (Object.assign(Object.assign({}, v), { rowIndex: index + 1 })));
        const results = result.filter(function (entry) {
            return entry.thread === concatIndex;
        });
        //const xplot = results[0].rowIndex * threadHeight;
        const xplot = (results[0] && results[0].rowIndex * getXScale()) - getXScale();
        return xplot;
        // const plot = (timelineNumber * threadHeight - threadHeight) * subThread;
        // return plot;
    };
    const CategoryBar = ({ label, height }) => {
        return (React.createElement("div", { className: classes.categoryBar, style: { height: height } }, React.createElement("div", { className: classes.categoryLabel }, React.createElement(Typography, { variant: "subtitle2" }, " ", label, " "))));
    };
    const DateMarkers = (React.createElement("div", null, filteredByDate &&
        showYearMarkers &&
        uniqueNodeScaleAmount >= summaryBreakpoint &&
        firstDayOfYearArray(filteredByDate).map((item, index) => {
            return (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    bottom: 0,
                    left: plotY(item.date)
                } }, React.createElement(MttYearTag, { year: true }, item.date.split('/')[2])));
        }), filteredByDate &&
        uniqueNodeScaleAmount >= summaryBreakpoint &&
        showMonthMarkers &&
        lastDayOfMonthArray(filteredByDate).map((item, index) => {
            return (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    bottom: 0,
                    left: plotY(item.date)
                } }, React.createElement(MttYearTag, null, convertNumberToMonths([item.date.split('/')[0]]))));
        }), filteredByDate &&
        uniqueNodeScaleAmount >= summaryBreakpoint &&
        Today(filteredByDate).map((item) => {
            return (React.createElement("div", { style: {
                    position: 'absolute',
                    bottom: 0,
                    left: plotY(item)
                } }, React.createElement(MttYearTag, { year: true, today: true }, React.createElement(Typography, { variant: "caption" }, " TODAY "))));
        })));
    // timeline render
    return (React.createElement("div", null, React.createElement("div", { ref: mainContainer, style: {
            position: 'relative',
            // top: 45,
            height: '75vh',
            overflow: 'scroll'
        } }, !loading && (React.createElement(React.Fragment, null, React.createElement("div", { style: { zIndex: 99999999, position: 'absolute', bottom: 0 } }, DateMarkers), data &&
        data &&
        uniqueNodeScaleAmount < summaryBreakpoint &&
        filteredByDate.map((item, index) => {
            return (React.createElement("div", { key: index, className: classes.categoryBarPlacement, style: {
                    top: plotCategoryBar(Number(item.timeline), Number(item.subThread)) + 0
                } }, React.createElement(CategoryBar, { key: item.id, label: item.timelineCategoryName, height: data && getXScale() })));
        }), data &&
        filteredByDate.map((item, index) => {
            return item.dates.length === 1 ? (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    left: plotY(new Date(item.date).toLocaleDateString('en-US')),
                    top: plotX(item.timeline, item.subThread),
                    //top: 0,
                    zIndex: 999999 -
                        plotY(new Date(item.date).toLocaleDateString('en-US')) -
                        item.subThread
                    //zIndex: 9999999 - index * index,
                } }, React.createElement(TimelineNode, { icon: React.createElement(IconRenderer, { noBorder: true, value: {
                        color: { hex: '#' + item.color },
                        name: item.iconID
                    } }), dot: data && uniqueNodeScaleAmount <= overviewBreakpoint, dotColor: '#' + item.color, data: item.dates, details: data && uniqueNodeScaleAmount < summaryBreakpoint, height: (data &&
                    uniqueNodeScaleAmount <= summaryBreakpoint &&
                    183) ||
                    (data &&
                        uniqueNodeScaleAmount <= overviewBreakpoint &&
                        30), width: data && uniqueNodeScaleAmount < summaryBreakpoint && 130, boxStyle: true, show: showAllDetails, iconColor: '#' + item.color }))) : (React.createElement("div", { key: item.id }, React.createElement("div", { style: {
                    position: 'absolute',
                    left: plotY(new Date(item.date).toLocaleDateString('en-US')) + 4,
                    top: plotX(item.timeline, item.subThread),
                    zIndex: 999999 -
                        plotY(new Date(item.date).toLocaleDateString('en-US')) -
                        item.timeline
                } }, React.createElement(MultiDot, { map: item.dates, number: item.dates.length }))));
        }), React.createElement(Fade, { in: data && uniqueNodeScaleAmount >= summaryBreakpoint }, React.createElement("div", null, data &&
        minnifiedResult.map((item, index) => {
            return (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    //zIndex: 0,
                    left: plotY(item.firstDate) + 2,
                    top: data && uniqueNodeScaleAmount > overviewBreakpoint
                        ? 14 + plotX(item.timeline, item.subThread)
                        : 4 + plotX(item.timeline, item.subThread)
                } }, React.createElement(TimelineWrapper, { timeline: item.timeline, style: {
                    width: plotY(item.lastDate) - plotY(item.firstDate) + 45,
                    height: data && uniqueNodeScaleAmount > overviewBreakpoint
                        ? 20
                        : 40,
                    backgroundColor: lighten('#' + item.color, 0.7)
                } })));
        }))), data && uniqueNodeScaleAmount < summaryBreakpoint && (React.createElement("div", null, React.createElement(GuideLinesShort, null)))))), React.createElement("div", { style: { width: 250 } }, React.createElement(HeightAdjuster, { verticalAdjuster: verticalAdjuster, setVerticalAdjuster: setVerticalAdjuster })), !loading && (React.createElement("div", { style: {
            position: 'relative',
            borderTop: '1px solid lightgrey',
            overflow: 'scroll'
        } }, React.createElement("div", null, data && displayRangeFilter && (React.createElement("div", { style: {
            overflow: 'scroll'
        } }, React.createElement("div", { key: data }, React.createElement(DynamicRangeSlider, { id: "range-slider", step: 10, threads: 10 * uniqueTimelines, width: containerWidth - rangeHandles, margin: topMargin +
            getInverseProportionalNumber(verticalAdjuster) * 3, defaultValue: [10, unique.length * 10], max: unique.length * 10, min: 10, onThumbDragEnd: processRangeValues, onRangeDragEnd: processRangeValues, onInput: (e) => getRangeValues(e) })))), React.createElement("div", null, data &&
        data.map((item, index) => {
            return item.dates.length === 1 ? (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    left: dataConvertedDate &&
                        plotYV(new Date(item.date).toLocaleDateString('en-US')) *
                            (containerWidth / unique.length) -
                            (visualizationSmall + rangeHandles),
                    top: plotXV(item.timeline, item.subThread) /
                        verticalAdjuster +
                        visualizationYScale +
                        adjusterHeight
                } }, React.createElement(VisualizationDot, { type: item.dates[0].details.shortDescription, hover: React.createElement(VisualizationCard, { title: item.dates[0].details.shortDescription, data: item.dates[0].details.data1, date: item.dates[0].details.date }) }))) : (React.createElement("div", { key: item.id }, React.createElement("div", { style: {
                    position: 'absolute',
                    left: dataConvertedDate &&
                        plotYV(new Date(item.date).toLocaleDateString('en-US')) *
                            (containerWidth / unique.length) -
                            (visualizationSmall + rangeHandles),
                    top: plotXV(item.timeline, item.subThread) /
                        verticalAdjuster +
                        visualizationYScale +
                        adjusterHeight
                } }, React.createElement(VisualizationDot, { hover: React.createElement("div", { style: { color: 'black' } }, item.dates.map((item) => {
                    return (React.createElement(VisualizationCardMulti, { title: item.details.description, date: item.details.date, key: item.id }));
                })), multi: true }, item.dates.length))));
        }))))), React.createElement("div", { style: { position: 'absolute', top: 0, left: 0, zIndex: 10 } }, loading &&
        preloadArray.map((item, index) => {
            return (React.createElement("div", { key: index, style: {
                    position: 'absolute',
                    left: Math.floor(Math.random() * 11) * 60 + 40,
                    top: (index + 1) * 80
                } }, React.createElement(TimelinePreloaderNode, { longView: true, loading: loading })));
        })), uniqueNodeScaleAmount >= summaryBreakpoint && (React.createElement("div", { style: {
            position: 'absolute',
            right: 0,
            top: 0,
            zIndex: 999999999,
            background: 'white',
            borderRadius: 4
        } }, React.createElement("div", { style: {
            display: 'flex',
            padding: theme.spacing(1),
            gap: theme.spacing(3)
        } }, legend, React.createElement(Button, { className: classes.button, onClick: () => setShowMonthMarkers(!showMonthMarkers) }, React.createElement("span", { style: { textDecoration: !showMonthMarkers && 'line-through' } })), React.createElement(Button, { className: classes.button, onClick: () => setShowYearMarkers(!showYearMarkers) }, React.createElement("span", { style: { textDecoration: !showYearMarkers && 'line-through' } })))))));
});
//# sourceMappingURL=MttTimeline.js.map