"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isItemType = exports.Item = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const style_1 = __importDefault(require("styled-jsx/style"));
const sdk_1 = require("@cntrl-site/sdk");
const RectangleItem_1 = require("./items/RectangleItem");
const ImageItem_1 = require("./items/ImageItem");
const VideoItem_1 = require("./items/VideoItem");
const RichTextItem_1 = require("./items/RichTextItem");
const VimeoEmbed_1 = require("./items/VimeoEmbed");
const YoutubeEmbed_1 = require("./items/YoutubeEmbed");
const CustomItem_1 = require("./items/CustomItem");
const useCntrlContext_1 = require("../provider/useCntrlContext");
const useItemPosition_1 = require("./useItemPosition");
const useItemDimensions_1 = require("./useItemDimensions");
const useItemScale_1 = require("./useItemScale");
const ScaleAnchorMap_1 = require("../utils/ScaleAnchorMap");
const useSectionHeightMap_1 = require("./useSectionHeightMap");
const HoverStyles_1 = require("../utils/HoverStyles/HoverStyles");
const getItemTopStyle_1 = require("../utils/getItemTopStyle");
const useStickyItemTop_1 = require("./items/useStickyItemTop");
const getAnchoredItemTop_1 = require("../utils/getAnchoredItemTop");
const useLayoutContext_1 = require("./useLayoutContext");
const ArticleRectContext_1 = require("../provider/ArticleRectContext");
const useExemplary_1 = require("../common/useExemplary");
const GroupItem_1 = require("./items/GroupItem");
const CodeEmbedItem_1 = require("./items/CodeEmbedItem");
const KeyframesContext_1 = require("../provider/KeyframesContext");
const itemsMap = {
    [sdk_1.ArticleItemType.Rectangle]: RectangleItem_1.RectangleItem,
    [sdk_1.ArticleItemType.Image]: ImageItem_1.ImageItem,
    [sdk_1.ArticleItemType.Video]: VideoItem_1.VideoItem,
    [sdk_1.ArticleItemType.RichText]: RichTextItem_1.RichTextItem,
    [sdk_1.ArticleItemType.YoutubeEmbed]: YoutubeEmbed_1.YoutubeEmbedItem,
    [sdk_1.ArticleItemType.VimeoEmbed]: VimeoEmbed_1.VimeoEmbedItem,
    [sdk_1.ArticleItemType.Custom]: CustomItem_1.CustomItem,
    [sdk_1.ArticleItemType.Group]: GroupItem_1.GroupItem,
    [sdk_1.ArticleItemType.CodeEmbed]: CodeEmbedItem_1.CodeEmbedItem
};
const stickyFix = `
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
`;
const RichTextWrapper = ({ isRichText, children }) => {
    if (!isRichText)
        return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
    return ((0, jsx_runtime_1.jsx)("div", { style: { transformOrigin: 'top left', transform: 'scale(var(--layout-deviation))' }, children: children }));
};
const noop = () => null;
const Item = ({ item, sectionId, articleHeight, isInGroup = false }) => {
    const itemWrapperRef = (0, react_1.useRef)(null);
    const rectObserver = (0, react_1.useContext)(ArticleRectContext_1.ArticleRectContext);
    const keyframesRepo = (0, react_1.useContext)(KeyframesContext_1.KeyframesContext);
    const id = (0, react_1.useId)();
    const keyframes = (0, react_1.useMemo)(() => keyframesRepo.getItemKeyframes(item.id), [keyframesRepo, item.id]);
    const { layouts } = (0, useCntrlContext_1.useCntrlContext)();
    const layout = (0, useLayoutContext_1.useLayoutContext)();
    const exemplary = (0, useExemplary_1.useExemplary)();
    const [wrapperHeight, setWrapperHeight] = (0, react_1.useState)(undefined);
    const [itemHeight, setItemHeight] = (0, react_1.useState)(undefined);
    const scale = (0, useItemScale_1.useItemScale)(item, sectionId);
    const position = (0, useItemPosition_1.useItemPosition)(item, sectionId);
    const sectionHeight = (0, useSectionHeightMap_1.useSectionHeightData)(sectionId);
    const stickyTop = (0, useStickyItemTop_1.useStickyItemTop)(item, sectionHeight, sectionId);
    const dimensions = (0, useItemDimensions_1.useItemDimensions)(item, sectionId);
    const layoutValues = [item.area, item.hidden, item.state.hover];
    const isInitialRef = (0, react_1.useRef)(true);
    layoutValues.push(item.sticky);
    layoutValues.push(sectionHeight);
    if (item.layoutParams) {
        layoutValues.push(item.layoutParams);
    }
    const sizing = layout && isItemType(item, sdk_1.ArticleItemType.RichText)
        ? item.layoutParams[layout].sizing
        : undefined;
    const sizingAxis = parseSizing(sizing);
    const ItemComponent = itemsMap[item.type] || noop;
    const sectionTop = rectObserver ? rectObserver.getSectionTop(sectionId) : 0;
    const handleItemResize = (height) => {
        if (!layout)
            return;
        const sticky = item.sticky[layout];
        if (!sticky || stickyTop === undefined) {
            setWrapperHeight(undefined);
            return;
        }
        const itemArticleOffset = sectionTop / window.innerWidth + stickyTop;
        const maxStickyTo = articleHeight - itemArticleOffset - height;
        const end = sticky.to
            ? Math.min(maxStickyTo, sticky.to)
            : articleHeight - itemArticleOffset - height;
        const wrapperHeight = end - sticky.from + height;
        setItemHeight(height);
        setWrapperHeight(wrapperHeight);
    };
    (0, react_1.useEffect)(() => {
        isInitialRef.current = false;
    }, []);
    const isRichText = isItemType(item, sdk_1.ArticleItemType.RichText);
    return ((0, jsx_runtime_1.jsxs)("div", { className: `item-wrapper-${item.id}`, ref: itemWrapperRef, style: Object.assign(Object.assign(Object.assign(Object.assign({}, (position ? { top: position.top } : {})), (position ? { left: position.left } : {})), (position ? { bottom: position.bottom } : {})), (wrapperHeight !== undefined ? { height: `${wrapperHeight * 100}vw` } : {})), children: [(0, jsx_runtime_1.jsx)("div", { suppressHydrationWarning: true, className: `item-${item.id}`, style: Object.assign({ opacity: (keyframes.length !== 0 && !layout) ? 0 : 1, top: `${stickyTop * 100}vw`, height: isRichText && itemHeight ? `${itemHeight * 100}vw` : 'unset' }, (scale !== undefined ? { transform: `scale(${scale}) translateZ(0)`, 'WebkitTransform': `scale(${scale}) translateZ(0)` } : {})), children: (0, jsx_runtime_1.jsx)(RichTextWrapper, { isRichText: isRichText, children: (0, jsx_runtime_1.jsx)("div", { className: `item-${item.id}-inner`, style: Object.assign({}, (dimensions ? {
                            width: `${sizingAxis.x === 'manual'
                                ? isRichText
                                    ? `${dimensions.width * exemplary}px`
                                    : `${dimensions.width * 100}vw`
                                : 'max-content'}`,
                            height: `${sizingAxis.y === 'manual' ? `${dimensions.height * 100}vw` : 'unset'}`
                        } : {})), children: (0, jsx_runtime_1.jsx)(ItemComponent, { item: item, sectionId: sectionId, onResize: handleItemResize, articleHeight: articleHeight }) }) }) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: id, children: `
        ${(0, sdk_1.getLayoutStyles)(layouts, layoutValues, ([area, hidden, hoverParams, sticky, sectionHeight, layoutParams], exemplary) => {
                    const sizingAxis = parseSizing(layoutParams.sizing);
                    const isScreenBasedBottom = area.positionType === sdk_1.PositionType.ScreenBased && area.anchorSide === sdk_1.AnchorSide.Bottom;
                    const scaleAnchor = area.scaleAnchor;
                    return (`
            .item-${item.id} {
              position: ${sticky ? 'sticky' : 'absolute'};
              top: ${sticky ? `${(0, getAnchoredItemTop_1.getAnchoredItemTop)(area.top - sticky.from, sectionHeight, area.anchorSide)}` : 0};
              pointer-events: auto;
              transition: opacity 0.2s linear 0.1s;
              display: ${hidden ? 'none' : 'block'};
              height: fit-content;
              transform-origin: ${ScaleAnchorMap_1.ScaleAnchorMap[scaleAnchor]};
              transform: scale(${area.scale});
            }
            .item-${item.id}-inner {
              transition: ${(0, HoverStyles_1.getTransitions)(['width', 'height', 'scale'], hoverParams)};
              width: ${sizingAxis.x === 'manual'
                        ? `${area.width * 100}vw`
                        : 'max-content'};
              height: ${sizingAxis.y === 'manual' ? `${area.height * 100}vw` : 'unset'};
            }
            .item-wrapper-${item.id} {
              position: ${area.positionType === sdk_1.PositionType.ScreenBased ? 'fixed' : 'absolute'};
              z-index: ${area.zIndex};
              ${!isInGroup && stickyFix}
              pointer-events: none;
              bottom: ${isScreenBasedBottom ? `${-area.top * 100}vw` : 'unset'};
              top: ${isScreenBasedBottom ? 'unset' : (0, getItemTopStyle_1.getItemTopStyle)(area.top, area.anchorSide)};
              left: ${area.left * 100}vw;
              transition: ${(0, HoverStyles_1.getTransitions)(['left', 'top'], hoverParams)};
            }
            .item-${item.id}-inner:hover {
              ${(0, HoverStyles_1.getHoverStyles)(['width', 'height', 'scale'], hoverParams)};
            }
            .item-wrapper-${item.id}:hover {
              ${(0, HoverStyles_1.getHoverStyles)(['left', 'top'], hoverParams, area.anchorSide)};
            }
          `);
                })}
      ` })] }));
};
exports.Item = Item;
function parseSizing(sizing = 'manual') {
    const axisSizing = sizing.split(' ');
    return {
        y: axisSizing[0],
        x: axisSizing[1] ? axisSizing[1] : axisSizing[0]
    };
}
function isItemType(item, itemType) {
    return item.type === itemType;
}
exports.isItemType = isItemType;
