"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("@builder.io/react");
var react_2 = require("react");
var isArray_1 = require("lodash-es/isArray");
var last_1 = require("lodash-es/last");
// import { get, isArray, last } from 'lodash';
var defaultTitle = {
    '@type': '@builder.io/sdk:Element',
    layerName: 'Accordion item title',
    responsiveStyles: {
        large: {
            marginTop: '10px',
            position: 'relative',
            display: 'flex',
            alignItems: 'stretch',
            flexDirection: 'column',
            paddingBottom: '10px'
        }
    },
    children: [
        {
            '@type': '@builder.io/sdk:Element',
            responsiveStyles: {
                large: {
                    textAlign: 'left',
                    display: 'flex',
                    flexDirection: 'column'
                }
            },
            component: {
                name: 'Text',
                options: {
                    text: 'I am an accordion title. Click me!'
                }
            }
        }
    ]
};
var defaultDetail = {
    '@type': '@builder.io/sdk:Element',
    layerName: 'Accordion item detail',
    responsiveStyles: {
        large: {
            position: 'relative',
            display: 'flex',
            alignItems: 'stretch',
            flexDirection: 'column',
            marginTop: '10px',
            paddingBottom: '10px'
        }
    },
    children: [
        {
            '@type': '@builder.io/sdk:Element',
            responsiveStyles: {
                large: {
                    paddingTop: '50px',
                    textAlign: 'left',
                    display: 'flex',
                    flexDirection: 'column',
                    paddingBottom: '50px'
                }
            },
            component: {
                name: 'Text',
                options: {
                    text: 'I am an accordion detail, hello!'
                }
            }
        }
    ]
};
// TODO: change to slick grid
var BuilderAccordionComponent = /** @class */ (function (_super) {
    __extends(BuilderAccordionComponent, _super);
    function BuilderAccordionComponent() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.divRef = null;
        _this.state = {
            open: []
        };
        return _this;
    }
    BuilderAccordionComponent.prototype.componentDidMount = function () {
        var _this = this;
        setTimeout(function () {
            if (_this.divRef) {
                _this.divRef.dispatchEvent(new CustomEvent('builder:accordion:load', {
                    bubbles: true,
                    cancelable: false,
                    detail: {
                        ref: _this
                    }
                }));
            }
        });
    };
    BuilderAccordionComponent.prototype.getAccordionItem = function (titleBlocks, detailBlocks, index, openGridItemOrder, onlyOneAtATime, fromChildren) {
        var _this = this;
        if (fromChildren === void 0) { fromChildren = false; }
        var open = this.state.open.indexOf(index) !== -1;
        var grid = this.props.grid;
        return (
        // This will not work as expected with react 15
        // Did preact get the span replacmenet too?
        react_2.default.createElement(react_2.default.Fragment, { key: index },
            react_2.default.createElement("div", { className: "builder-accordion-title builder-accordion-title-" + (open ? 'open' : 'closed'), style: __assign({ cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'stretch' }, (grid && __assign({ width: this.props.gridRowWidth }, (typeof openGridItemOrder === 'number' && {
                    order: index < openGridItemOrder ? index : index + 1
                })))), "data-index": index, onClick: function () {
                    if (open) {
                        _this.setState(__assign(__assign({}, _this.state), { open: onlyOneAtATime ? [] : _this.state.open.filter(function (item) { return item !== index; }) }));
                    }
                    else {
                        _this.setState(__assign(__assign({}, _this.state), { open: onlyOneAtATime ? [index] : _this.state.open.concat(index) }));
                    }
                } }, fromChildren ? (titleBlocks.map(function (block, index) { return (react_2.default.createElement(react_1.BuilderBlockComponent, { key: index, block: __assign(__assign({}, block), { repeat: null }), index: index, child: true })); })) : (react_2.default.createElement(react_1.BuilderBlocks, { blocks: titleBlocks, dataPath: "items." + index + ".title" }))),
            open && (react_2.default.createElement("div", { className: "builder-accordion-detail builder-accordion-detail-" + (open ? 'open' : 'closed'), style: __assign({ order: typeof openGridItemOrder === 'number' ? openGridItemOrder : undefined, maxHeight: this.props.animate ? (open ? '100vh' : 0) : undefined, transition: this.props.animate ? 'max-height 0.5s' : undefined }, (grid && {
                    width: '100%'
                })) }, open &&
                (fromChildren ? (detailBlocks.map(function (block, index) { return (react_2.default.createElement(react_1.BuilderBlockComponent, { key: index, block: __assign(__assign({}, block), { repeat: null }), index: index, child: true })); })) : (react_2.default.createElement(react_1.BuilderBlocks, { blocks: detailBlocks, dataPath: "items." + index + ".detail" })))))));
    };
    BuilderAccordionComponent.prototype.render = function () {
        var _this = this;
        var _a = this.props, grid = _a.grid, oneAtATime = _a.oneAtATime;
        var onlyOneAtATime = Boolean(grid || oneAtATime);
        var getOpenGridItemPosition = grid && this.state.open.length;
        var openGridItemOrder = null;
        if (getOpenGridItemPosition && this.divRef) {
            var openItemIndex = this.state.open[0];
            var openItem = this.divRef.querySelector(".builder-accordion-title[data-index=\"" + openItemIndex + "\"]");
            var subjectItem = openItem;
            openGridItemOrder = openItemIndex;
            if (subjectItem) {
                var prevItemRect = subjectItem.getBoundingClientRect();
                while ((subjectItem = subjectItem && subjectItem.nextElementSibling)) {
                    if (subjectItem) {
                        if (subjectItem.classList.contains('builder-accordion-detail')) {
                            continue;
                        }
                        var subjectItemRect = subjectItem.getBoundingClientRect();
                        if (subjectItemRect.left > prevItemRect.left) {
                            var index = parseInt(subjectItem.getAttribute('data-index') || '', 10);
                            if (!isNaN(index)) {
                                prevItemRect = subjectItemRect;
                                openGridItemOrder = index;
                            }
                        }
                        else {
                            break;
                        }
                    }
                }
            }
        }
        if (typeof openGridItemOrder === 'number') {
            openGridItemOrder = openGridItemOrder + 1;
        }
        return (react_2.default.createElement(react_1.BuilderAsyncRequestsContext.Consumer, null, function (value) {
            _this._errors = value && value.errors;
            _this._logs = value && value.logs;
            return (react_2.default.createElement(react_1.BuilderStoreContext.Consumer, null, function (state) { return (react_2.default.createElement("div", { ref: function (ref) { return (_this.divRef = ref); }, className: "builder-accordion", style: __assign({ display: 'flex', alignItems: 'stretch', flexDirection: 'column' }, (grid && {
                    flexDirection: 'row',
                    alignItems: 'flex-start',
                    flexWrap: 'wrap'
                })) }, _this.props.useChildrenForItems
                ? _this.props.builderBlock &&
                    _this.props.builderBlock.children &&
                    _this.props.builderBlock.children.map(function (block, index) {
                        if (block.repeat && block.repeat.collection) {
                            var collectionPath = block.repeat.collection;
                            var collectionName = last_1.default((collectionPath || '')
                                .split(/\.\w+\(/)[0]
                                .trim()
                                .split('.'));
                            var itemName_1 = block.repeat.itemName ||
                                (collectionName ? collectionName + 'Item' : 'item');
                            var array = react_1.stringToFunction(collectionPath, true, _this._errors, _this._logs)(state.state);
                            if (isArray_1.default(array)) {
                                return array.map(function (data, index) {
                                    var _a;
                                    // TODO: Builder state produce the data
                                    var childState = __assign(__assign({}, state.state), (_a = { $index: index, $item: data }, _a[itemName_1] = data, _a));
                                    return (react_2.default.createElement(react_1.BuilderStoreContext.Provider, { key: block.id, value: __assign(__assign({}, state), { state: childState }) }, _this.getAccordionItem(block.children ? [block.children[0]] : [], block.children ? [block.children[1]] : [], index, openGridItemOrder, onlyOneAtATime, true)));
                                });
                            }
                        }
                        return _this.getAccordionItem(block.children ? [block.children[0]] : [], block.children ? [block.children[1]] : [], index, openGridItemOrder, onlyOneAtATime, true);
                    })
                : _this.props.items &&
                    _this.props.items.map(function (item, index) {
                        return _this.getAccordionItem(item.title, item.detail, index, openGridItemOrder, onlyOneAtATime);
                    }))); }));
        }));
    };
    return BuilderAccordionComponent;
}(react_2.default.Component));
exports.BuilderAccordion = react_1.withBuilder(BuilderAccordionComponent, {
    name: 'Builder:Accordion',
    canHaveChildren: true,
    image: 'https://cdn.builder.io/api/v1/image/assets%2FagZ9n5CUKRfbL9t6CaJOyVSK4Es2%2Ffab6c1fd3fe542408cbdec078bca7f35',
    defaultStyles: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'stretch'
    },
    inputs: [
        {
            name: 'items',
            type: 'list',
            subFields: [
                {
                    name: 'title',
                    type: 'uiBlocks',
                    hideFromUI: true,
                    defaultValue: [defaultTitle]
                },
                {
                    name: 'detail',
                    type: 'uiBlocks',
                    hideFromUI: true,
                    defaultValue: [defaultDetail]
                }
            ],
            defaultValue: [
                {
                    title: [defaultTitle],
                    detail: [defaultDetail]
                },
                {
                    title: [defaultTitle],
                    detail: [defaultDetail]
                }
            ],
            showIf: function (options) { return !options.get('useChildrenForItems'); }
        },
        {
            name: 'oneAtATime',
            helperText: 'Only allow opening one at a time (collapse all others when new item openned)',
            type: 'boolean',
            defaultValue: false
        },
        {
            name: 'animate',
            helperText: 'Animate openning and closing',
            type: 'boolean',
            defaultValue: true
        },
        {
            name: 'grid',
            helperText: 'Display as a grid',
            type: 'boolean',
            defaultValue: false
        },
        {
            name: 'gridRowWidth',
            helperText: 'Display as a grid',
            type: 'string',
            showIf: function (options) { return options.get('grid'); },
            defaultValue: '25%'
        },
        {
            name: 'useChildrenForItems',
            type: 'boolean',
            helperText: 'Use child elements for each slide, instead of the array. Useful for dynamically repeating items',
            advanced: true,
            defaultValue: false,
            onChange: function (options) {
                if (options.get('useChildrenForItems') === true) {
                    options.set('items', []);
                }
            }
        }
        // TODO: best way to do this? how multiple, comma? All with "*"? Have as a per item option?
        // {
        //   name: 'defaultOpen',
        //   helperText: 'Number of the accordion item to have open default (e.g. choose 1 for the first)',
        // }
    ]
});
//# sourceMappingURL=Accordion.js.map