"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const useThrottledCallback_1 = __importDefault(require("../../hooks/useThrottledCallback"));
const useGraphHover_1 = __importDefault(require("../../hooks/useGraphHover"));
const varsUtilities_1 = require("../../varsUtilities");
const Text_1 = require("../Text");
const pretty_number_1 = require("@based/pretty-number");
const pretty_date_1 = require("@based/pretty-date");
const Legend = ({ isHover, x, values, xFormat, }) => {
    if (!values[0]?.svgX)
        return null;
    let baseColor = values[0].color
        ? values[0].color
        : values[0].label
            ? (0, varsUtilities_1.colorHash)('nonSemanticBackground', values[0].label)
            : 'violet';
    return (react_1.default.createElement("div", { style: {
            opacity: x && isHover ? 1 : 0,
            transition: 'opacity 0.5s',
            transform: x
                ? `translate3d(${values[0].svgX}px,0px,0px)`
                : 'translate3d(0px,0px,0px)',
            width: '1px',
            height: '100%',
            backgroundColor: (0, varsUtilities_1.color)('content', 'default', 'primary'),
        } },
        react_1.default.createElement("div", { style: {
                position: 'relative',
                transform: `translate3d(${-7.5}px, ${values[0].svgY - 7.5}px, 0px)`,
            } },
            react_1.default.createElement("div", { style: {
                    position: 'absolute',
                    borderRadius: '50%',
                    width: 15,
                    border: `2px solid ${(0, varsUtilities_1.color)('border', 'default', 'strong')} `,
                    backgroundColor: (0, varsUtilities_1.color)('nonSemanticBackground', baseColor, 'strong'),
                    //   backgroundColor: color(values[0].color || 'content','brand','default'),
                    height: 15,
                } }),
            values.slice(1).map((value, i) => (react_1.default.createElement("div", { key: i, style: {
                    position: 'absolute',
                    transform: `translate3d(${0}px, ${value.svgY - values[0].svgY}px, 0px)`,
                    borderRadius: '50%',
                    width: 15,
                    border: `2px solid ${(0, varsUtilities_1.color)('content', 'default', 'primary')} `,
                    // backgroundColor: color('action', 'primary', 'normal'),
                    backgroundColor: (0, varsUtilities_1.color)('nonSemanticBackground', value.color
                        ? value.color
                        : value.label
                            ? (0, varsUtilities_1.colorHash)('nonSemanticBackground', value.label)
                            : 'violet', 'strong'),
                    height: 15,
                } }))),
            react_1.default.createElement("div", { style: {
                    position: 'absolute',
                    left: isFlippedX ? -110 : 24,
                    padding: 8,
                    backgroundColor: (0, varsUtilities_1.color)('background', 'default', 'muted'),
                    border: `1px solid ${(0, varsUtilities_1.color)('border', 'default', 'strong')}`,
                    boxShadow: 'rgb(0 0 0 / 12%) 0px 4px 10px',
                    borderRadius: 4,
                    width: 'auto',
                    top: -30,
                    minWidth: 100,
                    transform: 'translateX(0%)',
                } },
                react_1.default.createElement("div", { style: {
                        paddingLeft: 10,
                        paddingRight: 10,
                        paddingTop: 5,
                        paddingBottom: 5,
                    } },
                    react_1.default.createElement(Text_1.Text, { weight: "strong" },
                        react_1.default.createElement("span", { style: {
                                color: (0, varsUtilities_1.color)('nonSemanticBackground', values[0].color
                                    ? values[0].color
                                    : values[0].label
                                        ? (0, varsUtilities_1.colorHash)('nonSemanticBackground', values[0].label)
                                        : 'violet', 'strong'),
                            } },
                            "\u2022",
                            ' '),
                        (0, pretty_number_1.prettyNumber)(values[0].y, values[0].valueFormat || 'number-short')),
                    values.slice(1).map((value, i) => (react_1.default.createElement(Text_1.Text, { key: i, weight: "strong" },
                        react_1.default.createElement("span", { style: {
                                color: (0, varsUtilities_1.color)('nonSemanticBackground', value.color
                                    ? value.color
                                    : value.label
                                        ? (0, varsUtilities_1.colorHash)('nonSemanticBackground', value.label)
                                        : 'violet', 'strong'),
                            } },
                            "\u2022",
                            ' '),
                        (0, pretty_number_1.prettyNumber)(value.y, value.valueFormat || 'number-short')))),
                    react_1.default.createElement(Text_1.Text, null,
                        "x:",
                        ' ',
                        xFormat === 'date-time-human'
                            ? (0, pretty_date_1.prettyDate)(values[0].x, 'date-time-human')
                            : xFormat === 'date'
                                ? (0, pretty_date_1.prettyDate)(values[0].x, 'time-precise') +
                                    ' - ' +
                                    (0, pretty_date_1.prettyDate)(values[0].x, 'date')
                                : (0, pretty_number_1.prettyNumber)(values[0].x, 'number-short')))))));
};
let isFlippedX = false;
const findPointAt = (path, x) => {
    let from = 0;
    let to = path.getTotalLength();
    let current = (from + to) / 2;
    let point = path.getPointAtLength(current);
    let count = 0;
    while (Math.abs(point.x - x) > 0.5 && count < 10) {
        count++;
        if (point.x < x)
            from = current;
        else
            to = current;
        current = (from + to) / 2;
        point = path.getPointAtLength(current);
    }
    return { point, position: current / path.getTotalLength() };
};
const getY = ({ x, width, isHover, data, lineRefs, xFormat, }) => {
    if (x < 0)
        return null;
    const values = Object.keys(data)
        .reduce((previous, key) => {
        if (!lineRefs[key]?.current)
            return previous;
        const box = lineRefs[key].current.getBBox();
        if (x < box.x || x > box.x + box.width) {
            return previous;
        }
        const { point } = findPointAt(lineRefs[key].current, x);
        return previous.concat({
            key,
            x: data[key].data[Math.floor((point.x / width) * data[key].data.length)]
                .x,
            y: data[key].data[Math.floor((point.x / width) * data[key].data.length)]
                .y,
            color: data[key].color,
            svgX: point.x,
            svgY: point.y,
            valueFormat: data[key].valueFormat,
            label: data[key].label,
        });
    }, [])
        .sort((a, b) => b.y - a.y);
    return (react_1.default.createElement(Legend
    // legend={legend}
    // isStacked={isStacked}
    , { 
        // legend={legend}
        // isStacked={isStacked}
        isHover: isHover, x: x, 
        // p={p}
        // xInfo={xInfo}
        // selected={selected}
        values: values, xFormat: xFormat }));
};
const Overlay = ({ isHover, x, width, data, r, isStacked, legend, ySpread, lineRefs, xFormat, }) => {
    return (react_1.default.createElement("div", { style: {
            pointerEvents: 'none',
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
        } }, x && x < width
        ? getY({
            x,
            width,
            r,
            isHover,
            data,
            isStacked,
            legend,
            ySpread,
            lineRefs,
            xFormat,
        })
        : null));
};
exports.default = ({ width, height, labelHeight = 0, labels, children, data, isStacked, legend, ySpread, lineRefs, xFormat, }) => {
    const [mouseX, setMouseX] = (0, react_1.useState)();
    const [hover, isHover] = (0, useGraphHover_1.default)();
    const ref = (0, react_1.useRef)();
    return (react_1.default.createElement("div", { style: {
            width,
            height,
            position: 'relative',
        }, 
        // @ts-ignore TODO fix
        onMouseMove: (0, useThrottledCallback_1.default)((event) => {
            const { x } = event.currentTarget.getBoundingClientRect();
            const mousePosX = event.clientX;
            if (window.innerWidth - mousePosX < 200) {
                isFlippedX = true;
            }
            else {
                isFlippedX = false;
            }
            // @ts-ignore
            setMouseX(event.pageX - x);
        }, []), ...hover },
        react_1.default.createElement("svg", { ref: ref, viewBox: `0 0 ${width} ${height}`, width: width, height: height },
            react_1.default.createElement("path", { d: `M0,0L${width},1`, stroke: (0, varsUtilities_1.color)('border', 'default', 'strong') }),
            labels.map((v, i) => {
                const y = (i + 1) * labelHeight;
                return (react_1.default.createElement("path", { key: i, d: `M0,${y}L${width},${y}`, stroke: (0, varsUtilities_1.color)('border', 'default', 'strong') }));
            }),
            children),
        react_1.default.createElement(Overlay, { isStacked: isStacked, legend: legend, isHover: isHover, x: mouseX, width: width, data: data, r: ref, ySpread: ySpread, lineRefs: lineRefs, xFormat: xFormat })));
};
//# sourceMappingURL=OverlayWrapper.js.map