'use strict';

require('@ui5/webcomponents-icons/dist/AllIcons.js');
require('@ui5/webcomponents/dist/BusyIndicator.js');
require('@ui5/webcomponents/dist/Icon.js');
var lit = require('lit');
var decorators_js = require('lit/decorators.js');
var engine = require('@digipair/engine');
var mermaid = require('mermaid/dist/mermaid.esm.min.mjs');
var unsafeHtml_js = require('lit/directives/unsafe-html.js');
var showdown = require('showdown');
var until_js = require('lit/directives/until.js');
var getCssSelectorOrigin = require('css-selector-generator');

function _interopNamespaceDefault(e) {
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n.default = e;
    return Object.freeze(n);
}

var showdown__namespace = /*#__PURE__*/_interopNamespaceDefault(showdown);

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator$1(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _ts_generator$1(thisArg, body) {
    var f, y, t, g, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    };
    return g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(_)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
function getBytes(stream, onChunk) {
    return _getBytes.apply(this, arguments);
}
function _getBytes() {
    _getBytes = _async_to_generator$1(function(stream, onChunk) {
        var reader, result;
        return _ts_generator$1(this, function(_state) {
            switch(_state.label){
                case 0:
                    reader = stream.getReader();
                    _state.label = 1;
                case 1:
                    return [
                        4,
                        reader.read()
                    ];
                case 2:
                    if (!!(result = _state.sent()).done) return [
                        3,
                        3
                    ];
                    onChunk(result.value);
                    return [
                        3,
                        1
                    ];
                case 3:
                    return [
                        2
                    ];
            }
        });
    });
    return _getBytes.apply(this, arguments);
}
function getLines(onLine) {
    var buffer;
    var position;
    var fieldLength;
    var discardTrailingNewline = false;
    return function onChunk(arr) {
        if (buffer === undefined) {
            buffer = arr;
            position = 0;
            fieldLength = -1;
        } else {
            buffer = concat(buffer, arr);
        }
        var bufLength = buffer.length;
        var lineStart = 0;
        while(position < bufLength){
            if (discardTrailingNewline) {
                if (buffer[position] === 10) {
                    lineStart = ++position;
                }
                discardTrailingNewline = false;
            }
            var lineEnd = -1;
            for(; position < bufLength && lineEnd === -1; ++position){
                switch(buffer[position]){
                    case 58:
                        if (fieldLength === -1) {
                            fieldLength = position - lineStart;
                        }
                        break;
                    case 13:
                        discardTrailingNewline = true;
                    case 10:
                        lineEnd = position;
                        break;
                }
            }
            if (lineEnd === -1) {
                break;
            }
            onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
            lineStart = position;
            fieldLength = -1;
        }
        if (lineStart === bufLength) {
            buffer = undefined;
        } else if (lineStart !== 0) {
            buffer = buffer.subarray(lineStart);
            position -= lineStart;
        }
    };
}
function getMessages(onId, onRetry, onMessage) {
    var message = newMessage();
    var decoder = new TextDecoder();
    return function onLine(line, fieldLength) {
        if (line.length === 0) {
            onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
            message = newMessage();
        } else if (fieldLength > 0) {
            var field = decoder.decode(line.subarray(0, fieldLength));
            var valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
            var value = decoder.decode(line.subarray(valueOffset));
            switch(field){
                case 'data':
                    message.data = message.data ? message.data + '\n' + value : value;
                    break;
                case 'event':
                    message.event = value;
                    break;
                case 'id':
                    onId(message.id = value);
                    break;
                case 'retry':
                    var retry = parseInt(value, 10);
                    if (!isNaN(retry)) {
                        onRetry(message.retry = retry);
                    }
                    break;
            }
        }
    };
}
function concat(a, b) {
    var res = new Uint8Array(a.length + b.length);
    res.set(a);
    res.set(b, a.length);
    return res;
}
function newMessage() {
    return {
        data: '',
        event: '',
        id: '',
        retry: undefined
    };
}

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _ts_generator(thisArg, body) {
    var f, y, t, g, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    };
    return g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(_)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
var __rest = undefined && undefined.__rest || function(s, e) {
    var t = {};
    for(var p in s)if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function") for(var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++){
        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
    }
    return t;
};
var EventStreamContentType = 'text/event-stream';
var DefaultRetryInterval = 1000;
var LastEventId = 'last-event-id';
function fetchEventSource(input, _a) {
    var inputSignal = _a.signal, inputHeaders = _a.headers, inputOnOpen = _a.onopen, onmessage = _a.onmessage, onclose = _a.onclose, onerror = _a.onerror, openWhenHidden = _a.openWhenHidden, inputFetch = _a.fetch, rest = __rest(_a, [
        "signal",
        "headers",
        "onopen",
        "onmessage",
        "onclose",
        "onerror",
        "openWhenHidden",
        "fetch"
    ]);
    return new Promise(function(resolve, reject) {
        var onVisibilityChange = function onVisibilityChange() {
            curRequestController.abort();
            if (!document.hidden) {
                create();
            }
        };
        var dispose = function dispose() {
            document.removeEventListener('visibilitychange', onVisibilityChange);
            window.clearTimeout(retryTimer);
            curRequestController.abort();
        };
        var create = function create() {
            return _create.apply(this, arguments);
        };
        var headers = Object.assign({}, inputHeaders);
        if (!headers.accept) {
            headers.accept = EventStreamContentType;
        }
        var curRequestController;
        if (!openWhenHidden) {
            document.addEventListener('visibilitychange', onVisibilityChange);
        }
        var retryInterval = DefaultRetryInterval;
        var retryTimer = 0;
        inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener('abort', function() {
            dispose();
            resolve();
        });
        var fetch = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
        var onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
        function _create() {
            _create = _async_to_generator(function() {
                var _$_a, response, err, interval;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            curRequestController = new AbortController();
                            _state.label = 1;
                        case 1:
                            _state.trys.push([
                                1,
                                5,
                                ,
                                6
                            ]);
                            return [
                                4,
                                fetch(input, Object.assign(Object.assign({}, rest), {
                                    headers: headers,
                                    signal: curRequestController.signal
                                }))
                            ];
                        case 2:
                            response = _state.sent();
                            return [
                                4,
                                onopen(response)
                            ];
                        case 3:
                            _state.sent();
                            return [
                                4,
                                getBytes(response.body, getLines(getMessages(function(id) {
                                    if (id) {
                                        headers[LastEventId] = id;
                                    } else {
                                        delete headers[LastEventId];
                                    }
                                }, function(retry) {
                                    retryInterval = retry;
                                }, onmessage)))
                            ];
                        case 4:
                            _state.sent();
                            onclose === null || onclose === void 0 ? void 0 : onclose();
                            dispose();
                            resolve();
                            return [
                                3,
                                6
                            ];
                        case 5:
                            err = _state.sent();
                            if (!curRequestController.signal.aborted) {
                                try {
                                    interval = (_$_a = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _$_a !== void 0 ? _$_a : retryInterval;
                                    window.clearTimeout(retryTimer);
                                    retryTimer = window.setTimeout(create, interval);
                                } catch (innerErr) {
                                    dispose();
                                    reject(innerErr);
                                }
                            }
                            return [
                                3,
                                6
                            ];
                        case 6:
                            return [
                                2
                            ];
                    }
                });
            });
            return _create.apply(this, arguments);
        }
        create();
    });
}
function defaultOnOpen(response) {
    var contentType = response.headers.get('content-type');
    if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
        throw new Error("Expected content-type to be ".concat(EventStreamContentType, ", Actual: ").concat(contentType));
    }
}

class InputsElement extends lit.LitElement {
    get values() {
        return Array.from(this.shadowRoot.children).map((el)=>({
                value: el.value,
                content: el.content,
                required: el.required
            }));
    }
    render() {
        const cache = JSON.stringify(this.inputs);
        if (this.cache === cache) {
            return lit.noChange;
        }
        this.cache = cache;
        return lit.html`
      ${(this.inputs || []).map((pins)=>lit.html`${until_js.until(engine.generateElementFromPins(pins, null, this.context).then((el)=>{
                setTimeout(()=>this.dispatchEvent(new CustomEvent('change')), 1);
                el.addEventListener('change', ()=>this.dispatchEvent(new CustomEvent('change')));
                return el;
            }), lit.nothing)}`)}
    `;
    }
    constructor(...args){
        super(...args);
        this.inputs = [];
        this.context = {};
        this.cache = '';
    }
}
__decorate([
    decorators_js.property({
        type: Array
    }),
    __metadata("design:type", Array)
], InputsElement.prototype, "inputs", void 0);
__decorate([
    decorators_js.property({
        type: Object
    }),
    __metadata("design:type", Object)
], InputsElement.prototype, "context", void 0);
InputsElement = __decorate([
    decorators_js.customElement('digipair-chatbot-inputs')
], InputsElement);

const WRITTING_IMAGE = 'data:image/gif;base64, ';

class ChatElement extends lit.LitElement {
    get inputs() {
        return this.inputsElement?.values || [];
    }
    static{
        this.styles = [
            lit.css`
      /* Pour Chrome et Edge */
      .container::-webkit-scrollbar {
        width: 8px; /* Largeur de la barre de défilement */
        background-color: transparent; /* Couleur de fond du rail de la barre de défilement */
      }

      .container::-webkit-scrollbar-thumb {
        background-color: #bfc1c3;
        border-radius: 10px; /* Pour rendre la barre de défilement arrondie */
        background-clip: padding-box;
        border: 2px solid transparent; /* Espace entre la barre de défilement et son rail */
      }

      .container::-webkit-scrollbar-track {
        background-color: transparent; /* Couleur de fond de la zone de défilement */
      }
      .container {
        position: absolute;
        top: 0;
        bottom: 70px;
        left: 0;
        right: 0;
        padding: 20px;
        overflow-y: scroll;
        margin-top: 1px;
        margin-bottom: 2px;
        margin-right: 3px;
      }

      .container > section {
        overflow: auto;
      }
      .container > section::-webkit-scrollbar {
        height: 8px; /* Largeur de la barre de défilement */
        background-color: transparent; /* Couleur de fond du rail de la barre de défilement */
      }
      .container > section::-webkit-scrollbar-thumb {
        background-color: #bfc1c3;
        border-radius: 10px; /* Pour rendre la barre de défilement arrondie */
        background-clip: padding-box;
        border: 2px solid transparent; /* Espace entre la barre de défilement et son rail */
      }
      .container > section::-webkit-scrollbar-track {
        background-color: transparent; /* Couleur de fond de la zone de défilement */
      }

      .assistant,
      .user {
        max-width: 70%; /* Largeur maximale des bulles de chat */
        padding: 10px 15px;
        margin-bottom: 10px;
        border-radius: 20px;
        line-height: 1.4;
      }

      .assistant {
        background-color: var(
          --digipair-color-primary,
          #52dfdb
        ); /* Couleur de fond des messages de l'assistant */
        color: var(
          --digipair-color-text-primary,
          #242e3b
        ); /* Couleur du texte des messages de l'assistant */
        align-self: flex-start;
        margin-right: auto;
      }

      .user {
        background-color: var(--digipair-color-secondary, #242e3b);
        color: var(
          --digipair-color-text-secondary,
          #ffffff
        ); /* Couleur du texte des messages de l'utilisateur */
        align-self: flex-end;
        margin-left: auto;
      }

      .assistant a {
        color: var(--digipair-color-text-primary, #242e3b);
      }

      .user a {
        color: var(--digipair-color-text-secondary, #ffffff);
      }

      .input-container {
        position: absolute;
        bottom: 0px;
        right: 0;
        left: 0;
        height: 50px;
        margin-top: 0px;
        padding-top: 10px;
        padding-left: 10px;
        padding-bottom: 10px;
        border-radius: 20px 5px 0px 20px;
        border: 1px solid rgba(112, 183, 253, 0.3);
      }

      .input-container input {
        outline: none;
        width: 250px;
        border-top: none;
        border-left: none;
        border-right: none;
        border-bottom: 1px solid #bababa;
        background-color: transparent;
        margin-right: 6px;
        padding-bottom: 0px;
      }

      .button {
        margin-left: 5px;
      }
      .button:not(.disabled) {
        cursor: pointer;
      }
      .button:hover:not(.disabled) {
        color: rgb(112, 183, 253);
      }
      .button.disabled {
        color: rgb(220 220 220);
      }

      .input {
        position: absolute;
        top: 0;
        bottom: 5px;
        left: 8px;
        right: 40px;
        margin-top: 5px;
        margin-left: 4px;
        margin-bottom: 5px;
      }

      #messageInput {
        width: 100%;
        height: 45px;
        border: none;
        outline: none;
        resize: none;
        background-color: white;
        color: black;
      }
      #messageInput::-webkit-scrollbar {
        width: 8px; /* Largeur de la barre de défilement */
        background-color: transparent; /* Couleur de fond du rail de la barre de défilement */
      }
      #messageInput::-webkit-scrollbar-thumb {
        background-color: #bfc1c3;
        border-radius: 10px; /* Pour rendre la barre de défilement arrondie */
        background-clip: padding-box;
        border: 2px solid transparent; /* Espace entre la barre de défilement et son rail */
      }
      #messageInput::-webkit-scrollbar-track {
        background-color: transparent; /* Couleur de fond de la zone de défilement */
      }

      p {
        margin: 0;
      }

      [name='microphone'] {
        position: absolute;
        right: 10px;
        top: 12px;
      }

      [name='begin'] {
        position: absolute;
        right: 10px;
        top: 40px;
      }

      .container.with-boost {
        bottom: 105px;
      }

      .input-container.with-boost {
        height: 85px;
      }

      .input .assistant {
        height: 18px;
        max-width: 100%;
        width: 235px;
        overflow: hidden;
        opacity: 0.3;
      }

      .input .assistant p {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }

      .button.action {
        float: right;
      }

      .loading {
        overflow: visible !important;
      }

      .loading .step {
        color: #bfc1c3;
        margin-left: 45px;
        padding-top: 15px;
        display: block;
      }

      .loading img {
        float: left;
      }

      .sources {
        margin-top: 10px;
      }

      .sources > .source {
        background-color: rgba(255, 255, 255, 0.5);
        font-size: 12px;
        color: rgb(60, 60, 60);
        padding: 0px 8px;
        display: inline-block;
        transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
        transform: scale(0.95);
        margin-bottom: 4px;
        border-radius: 5px;
        text-decoration: none;
        cursor: default;
      }

      .sources > .source.has-link {
        background-color: rgba(255, 255, 255, 0.9);
        cursor: pointer;
      }

      .sources > .source.has-link:hover {
        transform: scale(1);
      }

      .trust-bar {
        position: relative;
        width: 100%;
        height: 3px;
        background-color: rgba(82, 223, 219, 0.2);
        border-radius: 5px;
        overflow: hidden;
        margin-bottom: 5px;
      }

      .trust-bar-fill {
        height: 100%;
        background-color: green;
        transition: width 0.3s ease;
        border-radius: 5px;
      }

      .boosts {
        margin-top: 10px;
        margin-bottom: 5px;
      }

      .boosts.loading {
        display: none;
      }

      .boosts > .boost {
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 20px;
        font-size: 10px;
        color: rgb(60, 60, 60);
        padding: 4px 14px;
        cursor: pointer;
        display: inline-block;
        transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
        transform: scale(0.95);
        margin-bottom: 1px;
      }

      .boosts > .boost:hover {
        transform: scale(1);
      }
    `
        ];
    }
    connectedCallback() {
        super.connectedCallback();
        mermaid.initialize({
            startOnLoad: false
        });
        showdown__namespace.extension('mermaid', function() {
            return [
                {
                    type: 'lang',
                    filter: function(text) {
                        return text.replace(/```mermaid([^`]+)```/g, (_match, diagramCode)=>{
                            return '<div class="mermaid">' + diagramCode + '</div>';
                        });
                    }
                }
            ];
        });
        this.converter = new showdown__namespace.Converter({
            simplifiedAutoLink: true,
            strikethrough: true,
            tables: true,
            tasklists: true,
            smoothLivePreview: true
        });
        this.converter.addExtension('mermaid', {});
    }
    async addMessage(content) {
        if (this.currentBoost && !this.currentBoost.prompt) {
            this.dispatchEvent(new CustomEvent('prompt', {
                detail: {
                    prompt: ''
                }
            }));
            return;
        }
        this.messageInput.value = '';
        this.dispatchEvent(new CustomEvent('prompt', {
            detail: {
                prompt: content
            }
        }));
    }
    scrollDown() {
        const container = this.renderRoot.querySelector('.container');
        container.scrollTop = container.scrollHeight;
    }
    keypressManagement(event) {
        if (event.key !== 'Enter' || event.shiftKey) {
            this.requestUpdate();
            return;
        }
        if (this.currentBoost && !this.canAnswerToMessageBoost(this.currentBoost) || this.loading || (!this.messageInput || this.messageInput.value === '') && (!this.currentBoost || this.currentBoost.required) || !this.hasInputsValues()) {
            this.requestUpdate();
            return;
        }
        event.preventDefault();
        this.addMessage(this.messageInput.value.trim());
    }
    hasInputsValues() {
        return this.inputsElement.values.reduce((acc, { value, required })=>required && value === '' ? false : acc, true);
    }
    answer(message) {
        const boost = message.boost;
        this.dispatchEvent(new CustomEvent('boost', {
            detail: {
                parent_history: message.uuid,
                parent_conversation: message.parent_conversation || message.uuid,
                ...boost
            }
        }));
    }
    canAnswerToMessageBoost(boost) {
        if (!boost) {
            return false;
        }
        if (boost.checkUrl && !boost.checkUrl.test(window.location.href)) {
            return false;
        }
        if (boost.selector && !document.querySelector(boost.selector)) {
            return false;
        }
        return true;
    }
    executeBoost(boost) {
        this.dispatchEvent(new CustomEvent('executeboost', {
            detail: boost
        }));
    }
    getAvailableBoosts(boosts) {
        return boosts.filter((boost)=>boost && (boost.standalone || boost.selector) && (boost.standalone || document.querySelectorAll(boost.selector).length === 1)).map((boost)=>({
                ...boost,
                context: {
                    element: boost.standalone ? null : boost.selector
                },
                checkUrl: new RegExp(boost.url)
            })).filter((boost)=>boost.checkUrl.test(window.location.href));
    }
    pushMessage(message) {
        this.messages.push(message);
        this.requestUpdate();
    }
    render() {
        if (this.previousMessages !== JSON.stringify(this.messages)) {
            this.previousMessages = JSON.stringify(this.messages);
            setTimeout(()=>this.scrollDown(), 1);
        }
        setTimeout(()=>{
            this.renderRoot.querySelectorAll('.mermaid:not([data-processed=true]').forEach(async (el)=>{
                const { svg } = await mermaid.render('graphDiv', el.textContent);
                el.innerHTML = svg;
                el.setAttribute('data-processed', 'true');
            });
        }, 1);
        return lit.html`
      <section class="container ${this.currentBoost ? 'with-boost' : ''}">
        ${this.messages.map((message)=>lit.html`<section class="${message.role}">
              ${this.canAnswerToMessageBoost(message.boost) ? lit.html`<ui5-icon
                    name="response"
                    class="button action"
                    @click=${()=>this.answer(message)}
                  ></ui5-icon>` : lit.nothing}
              ${unsafeHtml_js.unsafeHTML(this.converter.makeHtml(message.role === 'user' ? message.content.replace(/\n/g, '  \n') : message.content.replace(/```markdown([\s\S]*?)```/g, (_, group)=>group)))}
            </section>`)}
        <digipair-chatbot-inputs
          @change=${()=>this.requestUpdate()}
          .inputs=${this.currentBoost?.inputs || []}
          .context=${{
            ...this.context,
            ...this.currentBoost?.context || {}
        }}
        ></digipair-chatbot-inputs>

        ${!this.loading ? lit.nothing : lit.html`<section class="loading">
              <img src=${WRITTING_IMAGE} /><span class="step">${this.loadingStep}</span>
            </section>`}
      </section>

      <section class="input-container ${this.currentBoost ? 'with-boost' : ''}">
        <section class="input">
          ${this.currentBoost?.parent_history ? lit.html`
                <section class="assistant">
                  ${this.messages.filter((message)=>message.uuid === this.currentBoost?.parent_history).map((message)=>lit.html`
                        <ui5-icon
                          name="decline"
                          class="button action"
                          @click=${()=>this.dispatchEvent(new CustomEvent('boost', {
                    detail: null
                }))}
                        ></ui5-icon>
                        ${unsafeHtml_js.unsafeHTML(this.converter.makeHtml(message.content.replace(/```markdown([\s\S]*?)```/g, (_, group)=>group)))}

                        <section class="sources">
                          ${message.sources?.map((source)=>lit.html`
                              <a
                                class="source ${source.document_url ? 'has-link' : ''}"
                                href=${source.document_url ?? 'javascript:'}
                                target="_blank"
                              >
                                ${source.document_name}
                                <div class="trust-bar">
                                  <div
                                    class="trust-bar-fill"
                                    style="width: ${source.rank * 100}%;"
                                  ></div>
                                </div>
                              </a>
                            `)}
                        </section>

                        <section class="actions ${this.loading ? 'loading' : ''}">
                          ${this.getAvailableBoosts(message.boosts || []).map((boost)=>lit.html`
                              <span class="action" @click=${()=>this.executeBoost(boost)}
                                >${boost.summary}</span
                              >
                            `)}
                        </section>
                      `)}
                </section>
              ` : lit.nothing}
          <textarea
            id="messageInput"
            value=""
            placeholder=${this.currentBoost && !this.currentBoost.prompt ? '' : 'Saisir votre message'}
            @keydown=${()=>this.requestUpdate()}
            @keyup=${(event)=>this.keypressManagement(event)}
            ?disabled=${this.loading || this.currentBoost && !this.currentBoost.prompt}
          ></textarea>
        </section>

        <ui5-icon
          name="begin"
          class="button ${this.currentBoost && !this.canAnswerToMessageBoost(this.currentBoost) || this.loading || (!this.messageInput || this.messageInput.value === '') && (!this.currentBoost || this.currentBoost.required) || !this.hasInputsValues() ? 'disabled' : ''}"
          @click=${()=>this.currentBoost && !this.canAnswerToMessageBoost(this.currentBoost) || this.loading || (!this.messageInput || this.messageInput.value === '') && (!this.currentBoost || this.currentBoost.required) || !this.hasInputsValues() ? void 0 : this.addMessage(this.messageInput.value.trim())}
        ></ui5-icon>
      </section>
    `;
    }
    constructor(...args){
        super(...args);
        this.previousMessages = '';
    }
}
__decorate([
    decorators_js.property({
        type: Boolean
    }),
    __metadata("design:type", Boolean)
], ChatElement.prototype, "loading", void 0);
__decorate([
    decorators_js.property({
        type: Array
    }),
    __metadata("design:type", Array)
], ChatElement.prototype, "messages", void 0);
__decorate([
    decorators_js.property({
        type: Object
    }),
    __metadata("design:type", Object)
], ChatElement.prototype, "currentBoost", void 0);
__decorate([
    decorators_js.property({
        type: Object
    }),
    __metadata("design:type", Object)
], ChatElement.prototype, "context", void 0);
__decorate([
    decorators_js.property({
        type: Array
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Array)
], ChatElement.prototype, "inputs", null);
__decorate([
    decorators_js.property(),
    __metadata("design:type", String)
], ChatElement.prototype, "loadingStep", void 0);
__decorate([
    decorators_js.query('#messageInput'),
    __metadata("design:type", typeof HTMLInputElement === "undefined" ? Object : HTMLInputElement)
], ChatElement.prototype, "messageInput", void 0);
__decorate([
    decorators_js.query('digipair-chatbot-inputs'),
    __metadata("design:type", typeof InputsElement === "undefined" ? Object : InputsElement)
], ChatElement.prototype, "inputsElement", void 0);
ChatElement = __decorate([
    decorators_js.customElement('digipair-chatbot-chat')
], ChatElement);

const styles$1 = lit.css`
  @keyframes bounce {
    from {
      width: 50px;
      height: 50px;
    }
    50% {
      width: 55px;
      height: 55px;
    }
    to {
      width: 50px;
      height: 50px;
    }
  }

  .container {
    position: fixed;
    z-index: 9999;
    right: 20px;
    bottom: 20px;
    line-height: 0.8;
  }

  .panel {
    position: absolute;
    top: -50px;
    right: 0px;
    height: 50px;
    border-radius: 20px 0 20px 20px;
    transition-property: width, background-color;
    transition-duration: 0.3s, 0.3s;
    transition-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275),
      cubic-bezier(0.175, 0.885, 0.32, 1.275);
    transition-delay: 0s, 0s;
    box-shadow: rgba(0, 0, 0, 0.25) 4px 0.25rem 0.25rem;
    border: 1px solid rgb(134, 255, 0);
    width: 50px;
    background-color: rgb(255, 255, 255);
  }

  .logo {
    width: 70px;
    height: 70px;
    position: absolute;
    right: -10px;
    top: -58px;
    transition: scale 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
  }

  .logo {
    cursor: pointer;
  }
  .logo:hover {
    scale: 1.1;
  }

  .actions {
    float: right;
    margin-right: 60px;
    margin-top: -38px;
  }

  .actions.loading {
    display: none;
  }

  .actions > .action {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 20px;
    font-size: 12px;
    color: rgb(60, 60, 60);
    padding: 8px 14px;
    cursor: pointer;
    display: inline-block;
    transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
    transform: scale(0.95);
    margin-bottom: 4px;
  }

  .actions > .action:hover {
    transform: scale(1);
  }

  .result {
    position: absolute;
    right: 0px;
    top: -500px;
    width: 340px;
    height: 440px;
    border-radius: 20px 5px 0px 20px;
    background-color: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.05) 0px 0.25rem 0.75rem;
    border: 1px solid rgb(134, 255, 0);
    color: rgb(60, 60, 60);
  }

  .result-closed .result {
    display: none;
  }
`;

function unescapeCSS(cssEscapedString) {
    return cssEscapedString.replace(/\\([0-9A-Fa-f]{1,6})\s?/g, (_match, charCode)=>String.fromCharCode(parseInt(charCode, 16))).replace(/\\/g, '');
}
function getCssSelector(element, options = {}) {
    const selector = getCssSelectorOrigin(element, options);
    return unescapeCSS(selector);
}

let DomService = class DomService {
    async executeRemoteReasoning({ digipair, reasoning, input, apiUrl }, _pinsSettingsList, context) {
        const response = await fetch(`${apiUrl}/${digipair}/${reasoning}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ...context.input,
                ...input
            })
        });
        const result = await response.json();
        if (response.status >= 400) {
            throw new Error(result.message);
        }
        return result;
    }
};
const executeRemoteReasoning = (params, pinsSettingsList, context)=>new DomService().executeRemoteReasoning(params, pinsSettingsList, context);

var actionsChatbot = /*#__PURE__*/Object.freeze({
    __proto__: null,
    executeRemoteReasoning: executeRemoteReasoning
});

engine.config.set('LIBRARIES', {
    '@digipair/actions-chatbot': actionsChatbot
});
const _config = {
    API_URL: window.location.origin,
    COMMON_EXPERIENCE: 'common'
};
const config = {
    set: (key, value)=>{
        if (key === 'LIBRARIES') {
            engine.config.set('LIBRARIES', {
                '@digipair/actions-chatbot': actionsChatbot,
                ...value
            });
            return;
        }
        if ([
            'BASE_URL',
            'VERSIONS'
        ].indexOf(key) >= 0) {
            engine.config.set('BASE_URL', value);
            return;
        }
        _config[key] = value;
    }
};

class ChatbotElement extends lit.LitElement {
    CHAT_COMMAND(digipair, reasoning) {
        return {
            library: '@digipair/actions-chatbot',
            element: 'executeRemoteReasoning',
            properties: {
                digipair,
                reasoning: reasoning ?? 'conversation',
                apiUrl: this.apiUrl
            }
        };
    }
    connectedCallback() {
        super.connectedCallback();
        this.loadUser();
        this.boostListener();
        this.externalBoostListener();
        this.initializeSSE();
        document.addEventListener('click', this.blurEvent);
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.blurEvent);
    }
    externalBoostListener() {
        this.addEventListener('executeBoost', ({ detail })=>{
            setTimeout(()=>this.executeBoost({
                    context: {},
                    ...detail
                }), 1);
        });
    }
    initializeSSE() {
        const digipair = this.code;
        const reasoning = 'notification';
        fetchEventSource(`${this.apiUrl}/${digipair}/${reasoning}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            onmessage: (message)=>{
                if (message.event !== 'message') {
                    return;
                }
                const data = JSON.parse(message.data);
                if (data.type === 'step') {
                    this.loadingStep = data.content;
                }
                if (data.type === 'message') {
                    this.pushMessage(data.content);
                }
            },
            body: JSON.stringify({
                userId: this.userId
            }),
            onerror (err) {
                console.error('[Digipair] SSE Error:', err);
            }
        });
    }
    loadUser() {
        this.newUser = false;
        if (this.userId) {
            return;
        }
        this.userId = localStorage.getItem('digipair-user');
        if (!this.userId) {
            // set uuid
            this.userId = Math.random().toString(36).substring(2, 15);
            localStorage.setItem('digipair-user', this.userId);
            this.newUser = true;
        }
    }
    async boostListener() {
        const boosts = (await this.executeScene('boosts')).map((boost)=>({
                ...boost,
                checkUrl: new RegExp(boost.url)
            })).filter((boost)=>boost.selector);
        let lastSelectedBoosts = [];
        document.addEventListener('mouseover', (event)=>{
            lastSelectedBoosts = event.target.closest('digipair-chatbot') ? null : this.getBoostsFromTarget(event.target, boosts);
            setTimeout(async ()=>{
                // si on est sur le chatbot, on ne fait rien
                if (!lastSelectedBoosts) {
                    return;
                }
                const selectedBoosts = this.getBoostsFromTarget(event.target, boosts);
                // garder les boosts communs entre les deux listes
                this.boosters = selectedBoosts.filter((boost)=>lastSelectedBoosts?.includes(boost)).map((boost)=>({
                        ...boost,
                        context: {
                            ...boost.context || {},
                            element: getCssSelector(event.target.closest(boost.selector))
                        }
                    }));
            }, 1000);
        }, true);
    }
    getBoostsFromTarget(target, boosts) {
        return boosts.filter((boost)=>boost.checkUrl.test(window.location.href) && !!target.closest(boost.selector));
    }
    async loadDigipair() {
        this.isDigipairLoading = true;
        const digipair = this.code;
        const reasoning = 'metadata';
        const metadata = await this.executeScene(reasoning);
        this.metadata = {
            ...metadata,
            id: digipair,
            config: {
                VERSIONS: metadata.config.VERSIONS
            }
        };
        await this.loadHistory();
        setTimeout(()=>{
            this.scrollDown();
            setTimeout(()=>{
                this.closeResult();
            }, 1);
        }, 1);
        this.isDigipairLoading = false;
        if (this.newUser) {
            this.manageNewUser();
        }
    }
    manageNewUser() {
        if (!this.firstOpenDelay) {
            return;
        }
        setTimeout(()=>{
            if (this.alreadyOpened) {
                return;
            }
            this.openResult();
        }, this.firstOpenDelay);
    }
    async loadHistory() {
        const userId = this.userId;
        const reasoning = 'history';
        const messages = (await this.executeScene(reasoning, {
            userId
        })).map((message)=>({
                ...message,
                boost: message.boost ? {
                    ...message.boost,
                    checkUrl: message.boost.url ? new RegExp(message.boost.url) : null
                } : null
            }));
        if (messages.length > 0) {
            this.messages = messages;
        }
    }
    scrollDown() {
        const container = this.shadowRoot.querySelector('.container');
        container.scrollTop = container.scrollHeight;
    }
    async execute(boost, message) {
        this.loadingStep = '';
        this.loading = true;
        if (message || boost?.command?.properties?.input?.prompt) {
            this.messages.push({
                role: 'user',
                content: message || boost.command.properties.input.prompt
            });
        }
        this.chatbot.requestUpdate();
        const command = boost?.command ? boost.command : this.CHAT_COMMAND(this.code, boost?.reasoning);
        try {
            const pins = JSON.parse(JSON.stringify(command));
            pins.properties = pins.properties || {};
            pins.properties.input = {
                ...pins.properties.input || {},
                prompt: message || pins.properties.input?.prompt,
                inputs: this.chatbot.inputs,
                userId: this.userId,
                step: boost?.step,
                parent_history: boost?.parent_history,
                parent_conversation: boost?.parent_conversation,
                context: boost?.context || {}
            };
            const detail = await engine.executePinsList([
                pins
            ], {
                config: {
                    VERSIONS: this.metadata.config.VERSIONS
                }
            }, 'boost');
            this.currentBoost = detail.boost ? {
                parent_history: detail.uuid,
                parent_conversation: detail.parent_conversation || detail.uuid,
                ...detail.boost
            } : null;
            this.pushMessage({
                role: 'assistant',
                content: detail.assistant,
                uuid: detail.uuid,
                boost: detail.boost,
                boosts: detail.boosts,
                sources: detail.sources,
                parent_conversation: detail.parent_conversation,
                parent_history: detail.parent_history
            });
            if (detail.command && detail.command.length > 0) {
                await engine.executePinsList(detail.command, {
                    config: {
                        VERSIONS: this.metadata.config.VERSIONS
                    }
                }, 'boost.command');
            }
        } catch (error) {
            this.pushMessage({
                role: 'assistant',
                content: 'Oops...'
            });
        }
        this.loadingStep = '';
        this.loading = false;
    }
    executeBoost(boost) {
        this.execute(boost);
        this.openResult();
        setTimeout(()=>{
            (this.chatbot?.shadowRoot?.querySelector('#messageInput')).focus();
        }, 1);
    }
    pushMessage(message) {
        this.openResult();
        this.messages.push(message);
        this.chatbot.requestUpdate();
    }
    openResult() {
        this.resultState = 'open';
        setTimeout(()=>{
            (this.chatbot?.shadowRoot?.querySelector('#messageInput')).focus();
            this.chatbot.requestUpdate();
        }, 1);
        this.alreadyOpened = true;
    }
    closeResult() {
        this.resultState = 'closed';
    }
    setBoost(boost) {
        this.currentBoost = boost;
        this.boosters = [];
    }
    static{
        this.styles = styles$1;
    }
    render() {
        if (this.metadata?.id !== this.code) {
            if (!this.isDigipairLoading) {
                this.loadDigipair();
            }
            return lit.html``;
        }
        return lit.html`
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
        font-family: 'Poppins', sans-serif;
        font-weight: 300;
        font-style: normal;

        --digipair-color-primary: ${this.metadata.primary};
        --digipair-color-text-primary: ${this.metadata.textPrimary};
        --digipair-color-secondary: ${this.metadata.secondary};
        --digipair-color-text-secondary: ${this.metadata.textSecondary};
      </style>

      <section class="container result-${this.resultState}">
        <section class="result" style="border: 1px solid var(--digipair-color-primary, #52DFDB)">
          <digipair-chatbot-chat
            ?loading=${this.loading}
            .messages=${this.messages}
            .currentBoost=${this.currentBoost}
            .context=${{
            config: this.metadata.config,
            variables: this.metadata.variables
        }}
            loadingStep=${this.loadingStep}
            @prompt=${(event)=>this.execute(this.currentBoost, event.detail.prompt)}
            @executeboost=${(event)=>this.executeBoost(event.detail)}
            @boost=${(event)=>this.setBoost(event.detail)}
          ></digipair-chatbot-chat>
        </section>

        <section class="actions ${this.loading ? 'loading' : ''}">
          ${this.boosters.map((boost)=>lit.html`
              <span
                class="action"
                style="border: 1px solid var(--digipair-color-primary, #52DFDB)"
                @click=${()=>this.executeBoost(boost)}
                >${boost.summary}</span
              >
            `)}
        </section>

        <section
          class="panel"
          style="border: 1px solid var(--digipair-color-primary, #52DFDB)"
        ></section>
        <img
          @click=${()=>this.resultState !== 'closed' ? this.closeResult() : this.openResult()}
          class="logo ${this.loading ? 'loading' : ''}"
          src="${this.apiUrl}/${this.code}/avatar.png"
          alt="Agent Avatar"
        />
      </section>
    `;
    }
    constructor(...args){
        super(...args);
        this.code = 'common';
        this.firstOpenDelay = 60000;
        this.apiUrl = _config.API_URL;
        this.userId = null;
        this.boosters = [];
        this.loading = false;
        this.resultState = 'open';
        this.currentBoost = null;
        this.messages = [];
        this.loadingStep = '';
        this.alreadyOpened = false;
        this.isDigipairLoading = false;
        this.blurEvent = (event)=>{
            const path = event.composedPath();
            if (!path.includes(this)) {
                // L'événement a été déclenché en dehors du composant
                this.closeResult();
            }
        };
        this.executeScene = async (reasoning, input = {})=>{
            const digipair = this.code;
            const response = await fetch(`${this.apiUrl}/${digipair}/${reasoning}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(input)
            });
            return await response.json();
        };
    }
}
__decorate([
    decorators_js.property()
], ChatbotElement.prototype, "code", void 0);
__decorate([
    decorators_js.property()
], ChatbotElement.prototype, "firstOpenDelay", void 0);
__decorate([
    decorators_js.property()
], ChatbotElement.prototype, "apiUrl", void 0);
__decorate([
    decorators_js.property(),
    __metadata("design:type", Object)
], ChatbotElement.prototype, "userId", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Array)
], ChatbotElement.prototype, "boosters", void 0);
__decorate([
    decorators_js.state()
], ChatbotElement.prototype, "loading", void 0);
__decorate([
    decorators_js.state()
], ChatbotElement.prototype, "resultState", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Object)
], ChatbotElement.prototype, "currentBoost", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Array)
], ChatbotElement.prototype, "messages", void 0);
__decorate([
    decorators_js.state()
], ChatbotElement.prototype, "loadingStep", void 0);
__decorate([
    decorators_js.query('digipair-chatbot-chat'),
    __metadata("design:type", typeof ChatElement === "undefined" ? Object : ChatElement)
], ChatbotElement.prototype, "chatbot", void 0);
ChatbotElement = __decorate([
    decorators_js.customElement('digipair-chatbot')
], ChatbotElement);

const styles = lit.css`
  @keyframes bounce {
    from {
      width: 50px;
      height: 50px;
    }
    50% {
      width: 55px;
      height: 55px;
    }
    to {
      width: 50px;
      height: 50px;
    }
  }

  .container {
    position: absolute;
    top: 20px;
    bottom: 20px;
    right: 20px;
    left: 20px;
    line-height: 0.8;
  }

  .panel {
    position: absolute;
    top: -5px;
    right: -5px;
    height: 50px;
    border-radius: 20px 0 20px 20px;
    transition-property: width, background-color;
    transition-duration: 0.3s, 0.3s;
    transition-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275),
      cubic-bezier(0.175, 0.885, 0.32, 1.275);
    transition-delay: 0s, 0s;
    box-shadow: rgba(0, 0, 0, 0.25) 4px 0.25rem 0.25rem;
    border: 1px solid rgb(134, 255, 0);
    width: 50px;
    background-color: rgb(255, 255, 255);
  }

  .logo {
    width: 70px;
    height: 70px;
    position: absolute;
    right: -15px;
    top: -15px;
    transition: scale 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
  }

  .logo {
    cursor: pointer;
  }
  .logo:hover {
    scale: 1.1;
  }

  .actions {
    position: absolute;
    right: -5px;
    top: 62px;
    text-align: right;
  }

  .actions.loading {
    display: none;
  }

  .actions .action {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 20px;
    font-size: 12px;
    color: rgb(60, 60, 60);
    padding: 8px 14px;
    cursor: pointer;
    display: inline-block;
    transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0s;
    transform: scale(0.95);
    margin-bottom: 4px;
  }

  .actions .action:hover {
    transform: scale(1);
  }

  .result {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    border-radius: 20px 5px 0px 20px;
    background-color: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.05) 0px 0.25rem 0.75rem;
    border: 1px solid rgb(134, 255, 0);
    color: rgb(60, 60, 60);
  }
`;

class DigipairFullElement extends lit.LitElement {
    CHAT_COMMAND(digipair, reasoning) {
        return {
            library: '@digipair/actions-chatbot',
            element: 'executeRemoteReasoning',
            properties: {
                digipair,
                reasoning: reasoning ?? 'conversation',
                apiUrl: this.apiUrl
            }
        };
    }
    connectedCallback() {
        super.connectedCallback();
        this.loadUser();
        this.loadBoosters();
        this.initializeSSE();
    }
    initializeSSE() {
        const digipair = this.code;
        const reasoning = 'notification';
        fetchEventSource(`${this.apiUrl}/${digipair}/${reasoning}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            onmessage: (message)=>{
                if (message.event !== 'message') {
                    return;
                }
                const data = JSON.parse(message.data);
                if (data.type === 'step') {
                    this.loadingStep = data.content;
                }
                if (data.type === 'message') {
                    this.pushMessage(data.content);
                }
            },
            body: JSON.stringify({
                userId: this.userId
            }),
            onerror (err) {
                console.error('[Digipair] SSE Error:', err);
            }
        });
    }
    loadUser() {
        if (this.userId) {
            return;
        }
        this.userId = localStorage.getItem('digipair-user');
        if (!this.userId) {
            // set uuid
            this.userId = Math.random().toString(36).substring(2, 15);
            localStorage.setItem('digipair-user', this.userId);
        }
    }
    async loadBoosters() {
        this.cacheBoosters = (await this.executeScene('boosts')).map((boost)=>({
                ...boost,
                checkUrl: new RegExp(boost.url)
            })).filter((boost)=>boost.standalone);
    }
    async loadDigipair() {
        this.isDigipairLoading = true;
        const digipair = this.code;
        const reasoning = 'metadata';
        const metadata = await this.executeScene(reasoning);
        this.metadata = {
            ...metadata,
            id: digipair,
            config: {
                VERSIONS: metadata.config.VERSIONS
            }
        };
        await this.loadHistory();
        setTimeout(()=>{
            this.scrollDown();
        }, 1);
        this.isDigipairLoading = false;
    }
    async loadHistory() {
        const userId = this.userId;
        const reasoning = 'history';
        const messages = (await this.executeScene(reasoning, {
            userId
        })).map((message)=>({
                ...message,
                boost: message.boost ? {
                    ...message.boost,
                    checkUrl: message.boost.url ? new RegExp(message.boost.url) : null
                } : null
            }));
        if (messages.length > 0) {
            this.messages = messages;
        }
    }
    scrollDown() {
        const container = this.shadowRoot.querySelector('.container');
        container.scrollTop = container.scrollHeight;
    }
    async execute(boost, message) {
        this.loadingStep = '';
        this.loading = true;
        if (message || boost?.command?.properties?.input?.prompt) {
            this.messages.push({
                role: 'user',
                content: message || boost.command.properties.input.prompt
            });
        }
        this.chatbot.requestUpdate();
        const command = boost?.command ? boost.command : this.CHAT_COMMAND(this.code, boost?.reasoning);
        try {
            const pins = JSON.parse(JSON.stringify(command));
            pins.properties = pins.properties || {};
            pins.properties.input = {
                ...pins.properties.input || {},
                prompt: message || pins.properties.input?.prompt,
                inputs: this.chatbot.inputs,
                userId: this.userId,
                step: boost?.step,
                parent_history: boost?.parent_history,
                parent_conversation: boost?.parent_conversation,
                context: boost?.context || {},
                ...!boost ? {} : {
                    boost: {
                        name: boost.name,
                        text: boost.text
                    }
                }
            };
            const detail = await engine.executePinsList([
                pins
            ], {
                config: {
                    VERSIONS: this.metadata.config.VERSIONS
                }
            }, 'boost');
            this.currentBoost = detail.boost ? {
                parent_history: detail.uuid,
                parent_conversation: detail.parent_conversation || detail.uuid,
                ...detail.boost
            } : null;
            this.pushMessage({
                role: 'assistant',
                content: detail.assistant,
                uuid: detail.uuid,
                boost: detail.boost,
                boosts: detail.boosts,
                sources: detail.sources,
                parent_conversation: detail.parent_conversation,
                parent_history: detail.parent_history
            });
            if (detail.command && detail.command.length > 0) {
                engine.executePinsList(detail.command, {
                    config: {
                        VERSIONS: this.metadata.config.VERSIONS
                    }
                }, 'boost.command');
            }
        } catch (error) {
            this.pushMessage({
                role: 'assistant',
                content: 'Oops...'
            });
        }
        this.loadingStep = '';
        this.loading = false;
    }
    executeBoost(boost) {
        this.execute(boost);
        this.closeMenu();
        setTimeout(()=>{
            (this.chatbot?.shadowRoot?.querySelector('#messageInput')).focus();
        }, 1);
    }
    pushMessage(message) {
        this.messages.push(message);
        this.chatbot.requestUpdate();
    }
    async openMenu() {
        this.boosters = this.cacheBoosters;
    }
    closeMenu() {
        this.boosters = [];
    }
    setBoost(boost) {
        this.currentBoost = boost;
        this.boosters = [];
    }
    static{
        this.styles = styles;
    }
    render() {
        if (this.metadata?.id !== this.code) {
            if (!this.isDigipairLoading) {
                this.loadDigipair();
            }
            return lit.html``;
        }
        return lit.html`
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
        font-family: 'Poppins', sans-serif;
        font-weight: 300;
        font-style: normal;

        --digipair-color-primary: ${this.metadata.primary};
        --digipair-color-primary: ${this.metadata.secondary};
        --digipair-color-text-primary: ${this.metadata.textPrimary};
        --digipair-color-text-primary: ${this.metadata.textSecondary};
      </style>

      <section class="container">
        <section class="result" style="border: 1px solid var(--digipair-color-primary, #52DFDB)">
          <digipair-chatbot-chat
            ?loading=${this.loading}
            .messages=${this.messages}
            .currentBoost=${this.currentBoost}
            .context=${{
            config: this.metadata.config,
            variables: this.metadata.variables
        }}
            loadingStep=${this.loadingStep}
            @prompt=${(event)=>this.execute(this.currentBoost, event.detail.prompt)}
            @boost=${(event)=>this.setBoost(event.detail)}
            @executeboost=${(event)=>this.executeBoost(event.detail)}
          ></digipair-chatbot-chat>
        </section>

        <section class="actions ${this.loading ? 'loading' : ''}">
          ${this.boosters.map((boost)=>lit.html`
              <div>
                <span
                  class="action"
                  style="border: 1px solid var(--digipair-color-primary, #52DFDB)"
                  @click=${()=>this.executeBoost(boost)}
                  >${boost.summary}</span
                >
              </div>
            `)}
        </section>

        <section
          class="panel"
          style="border: 1px solid var(--digipair-color-primary, #52DFDB)"
        ></section>
        <img
          class="logo ${this.loading ? 'loading' : ''}"
          src=${this.metadata.avatar}
          @click=${()=>this.boosters.length <= 0 ? this.openMenu() : this.closeMenu()}
        />
      </section>
    `;
    }
    constructor(...args){
        super(...args);
        this.code = 'common';
        this.apiUrl = _config.API_URL;
        this.userId = null;
        this.boosters = [];
        this.loading = false;
        this.currentBoost = null;
        this.messages = [];
        this.loadingStep = '';
        this.cacheBoosters = [];
        this.isDigipairLoading = false;
        this.executeScene = async (reasoning, input = {})=>{
            const digipair = this.code;
            const response = await fetch(`${this.apiUrl}/${digipair}/${reasoning}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(input)
            });
            return await response.json();
        };
    }
}
__decorate([
    decorators_js.property()
], DigipairFullElement.prototype, "code", void 0);
__decorate([
    decorators_js.property()
], DigipairFullElement.prototype, "apiUrl", void 0);
__decorate([
    decorators_js.property(),
    __metadata("design:type", Object)
], DigipairFullElement.prototype, "userId", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Array)
], DigipairFullElement.prototype, "boosters", void 0);
__decorate([
    decorators_js.state()
], DigipairFullElement.prototype, "loading", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Object)
], DigipairFullElement.prototype, "currentBoost", void 0);
__decorate([
    decorators_js.state(),
    __metadata("design:type", Array)
], DigipairFullElement.prototype, "messages", void 0);
__decorate([
    decorators_js.state()
], DigipairFullElement.prototype, "loadingStep", void 0);
__decorate([
    decorators_js.query('digipair-chatbot-chat'),
    __metadata("design:type", typeof ChatElement === "undefined" ? Object : ChatElement)
], DigipairFullElement.prototype, "chatbot", void 0);
DigipairFullElement = __decorate([
    decorators_js.customElement('digipair-chatbot-full')
], DigipairFullElement);

exports.ChatbotElement = ChatbotElement;
exports.DigipairFullElement = DigipairFullElement;
exports.config = config;
