import { r as registerInstance, c as createEvent, h, H as Host } from './index-BIwHMk6j.js';
import { L as Le } from './index.esm-CMeGYws2.js';
import { i as isLimeQuerySupported } from './lime-query-validation-DvCLebd2.js';
import './property-resolution-CQUZjrU4.js';

const limeQueryBuilderCss = () => `*,*:before,*:after{box-sizing:border-box}:host(limebb-lime-query-builder){--header-background-color:rgb(var(--contrast-500));--limebb-lime-query-builder-background-color:rgb(var(--contrast-100));--limebb-lime-query-builder-border-radius:0.75rem;--limebb-lime-query-builder-visual-mode-padding:1rem;--limebb-lime-query-builder-group-color:rgb(var(--color-sky-lighter));box-sizing:border-box;width:calc(100% - 1.5rem);margin:0.75rem auto;display:flex;flex-direction:column;border-radius:var(--limebb-lime-query-builder-border-radius);background-color:var(--limebb-lime-query-builder-background-color);box-shadow:var(--shadow-inflated-16)}.visual-mode{display:flex;flex-direction:column;gap:1rem;padding:var(--limebb-lime-query-builder-visual-mode-padding);border:1px solid var(--header-background-color);border-radius:0 0 var(--limebb-lime-query-builder-border-radius) var(--limebb-lime-query-builder-border-radius)}.code-mode{--code-editor-max-height:70vh;display:flex;flex-direction:column;gap:1rem}.code-mode .validation-errors{padding:0.75rem 1rem;color:rgb(var(--color-red-default));background-color:rgb(var(--color-red-lighter));border-left:0.25rem solid rgb(var(--color-red-default));border-radius:0.25rem;font-size:0.875rem}.code-mode .validation-errors strong{display:block;margin-bottom:0.5rem;font-weight:600}.code-mode .validation-errors ul{margin:0;padding-left:1.5rem}.code-mode .validation-errors li{margin:0.25rem 0}.code-mode .visual-mode-limitations{padding:0.75rem 1rem;color:rgb(var(--color-blue-dark));background-color:rgb(var(--color-blue-lighter));border-left:0.25rem solid rgb(var(--color-blue-default));border-radius:0.25rem;font-size:0.875rem}.code-mode .visual-mode-limitations strong{display:block;margin-bottom:0.5rem;font-weight:600}.code-mode .visual-mode-limitations ul{margin:0;padding-left:1.5rem}.code-mode .visual-mode-limitations li{margin:0.25rem 0}section.description,section.filter,section.query-options{display:flex;flex-direction:column;gap:1rem}section h4{margin:0;font-size:1.125rem;font-weight:600;color:rgb(var(--contrast-1000))}limel-header.is-narrow{--header-top-right-left-border-radius:0;width:calc(100% + var(--limebb-lime-query-builder-visual-mode-padding) * 2);margin-left:calc(var(--limebb-lime-query-builder-visual-mode-padding) * -1)}.query-options-controls{display:flex;flex-direction:column;gap:1rem}`;

var __decorate = (undefined && undefined.__decorate) || function (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;
};
const LimeQueryBuilder = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.change = createEvent(this, "change");
        this.mode = 'visual';
        this.codeValue = '';
        this.limetype = '';
        this.handleLimetypeChange = (event) => {
            event.stopPropagation();
            this.limetype = event.detail;
            // Reset filter when limetype changes
            this.filter = undefined;
            // Reset response format when limetype changes - empty state
            this.internalResponseFormat = {
                object: {},
            };
            this.emitChange();
        };
        this.handleFilterChange = (event) => {
            var _a;
            event.stopPropagation();
            this.filter = (_a = event.detail) !== null && _a !== void 0 ? _a : undefined;
            this.emitChange();
        };
        this.handleResponseFormatChange = (event) => {
            event.stopPropagation();
            this.internalResponseFormat = event.detail;
            this.emitChange();
        };
        this.handleLimitChange = (event) => {
            event.stopPropagation();
            const value = event.detail;
            this.limit = value ? Number.parseInt(value, 10) : undefined;
            this.emitChange();
        };
        this.handleOrderByChange = (event) => {
            event.stopPropagation();
            this.orderBy = event.detail;
            this.emitChange();
        };
        this.handleDescriptionChange = (event) => {
            event.stopPropagation();
            this.description = event.detail || undefined;
            this.emitChange();
        };
        this.handleDescriptionBlur = () => {
            if (this.description) {
                const trimmed = this.description.trim();
                if (trimmed !== this.description) {
                    this.description = trimmed || undefined;
                    this.emitChange();
                }
            }
        };
        this.handleChange = (event) => {
            event.stopPropagation();
            const mode = event.detail.id;
            if (mode === 'visual') {
                try {
                    const parsed = JSON.parse(this.codeValue);
                    const support = this.checkVisualModeSupport();
                    if (!support.visualModeSupported) {
                        return;
                    }
                    this.limetype = parsed.limetype || '';
                    this.filter = parsed.filter;
                    this.internalResponseFormat = parsed.responseFormat;
                    this.limit = parsed.limit;
                    this.orderBy = parsed.orderBy;
                    this.description = parsed['#description'];
                    this.mode = 'visual';
                    this.change.emit(parsed);
                }
                catch (_a) {
                    // Don't switch if JSON is invalid
                }
            }
            else if (mode === 'code') {
                this.updateCodeValue();
                this.mode = 'code';
            }
        };
        this.handleCodeChange = (event) => {
            event.stopPropagation();
            this.codeValue = event.detail;
            // Try to parse and emit if valid
            try {
                const parsed = JSON.parse(this.codeValue);
                this.change.emit(parsed);
            }
            catch (_a) {
                // Don't emit invalid JSON (linter will show the error)
            }
        };
    }
    // Buttons are generated dynamically in renderModeSwitch to allow disabling
    getButtons() {
        return [
            {
                id: 'visual',
                title: 'Visual',
            },
            { id: 'code', title: 'Code' },
        ];
    }
    get visualModeEnabled() {
        var _a, _b, _c;
        return ((_c = (_b = (_a = this.platform) === null || _a === void 0 ? void 0 : _a.isFeatureEnabled) === null || _b === void 0 ? void 0 : _b.call(_a, 'useLimeQueryBuilderGuiMode')) !== null && _c !== void 0 ? _c : false);
    }
    componentWillLoad() {
        // Force code mode if visual mode is disabled
        if (!this.visualModeEnabled) {
            this.mode = 'code';
            // Initialize code value from prop
            this.updateCodeValue();
            return;
        }
        if (this.value) {
            this.limetype = this.value.limetype || '';
            this.filter = this.value.filter;
            this.internalResponseFormat = this.value.responseFormat;
            this.limit = this.value.limit;
            this.orderBy = this.value.orderBy;
            this.description = this.value['#description'];
        }
        // Initialize code value from prop
        this.updateCodeValue();
        // Check if visual mode is supported
        const support = this.checkVisualModeSupport();
        if (!support.visualModeSupported) {
            this.mode = 'code';
        }
    }
    render() {
        return (h(Host, { key: '9a121529165f1691e32b2b156b128977c5b5ba3a' }, this.renderHeader(), this.renderContent()));
    }
    renderContent() {
        const visualModeSupported = this.checkVisualModeSupport();
        const showCodeMode = !this.visualModeEnabled || this.mode === 'code';
        return showCodeMode
            ? this.renderCodeMode(visualModeSupported)
            : this.renderVisualMode();
    }
    emitChange() {
        // Only emit in visual mode
        if (this.mode === 'code') {
            return;
        }
        if (!this.limetype) {
            return;
        }
        this.change.emit(this.buildLimeQuery());
    }
    updateCodeValue() {
        if (!this.limetype) {
            this.codeValue = JSON.stringify(this.value || {}, null, 2);
            return;
        }
        this.codeValue = JSON.stringify(this.buildLimeQuery(), null, 2);
    }
    buildLimeQuery() {
        // Use internal state, then default to returning just _id
        const responseFormat = this.internalResponseFormat || {
            object: {
                _id: null,
            },
        };
        const limeQuery = {
            limetype: this.limetype,
            responseFormat: responseFormat,
            filter: this.filter,
        };
        if (this.description) {
            limeQuery['#description'] = this.description;
        }
        if (this.limit !== undefined && this.limit > 0) {
            limeQuery.limit = this.limit;
        }
        if (this.orderBy && this.orderBy.length > 0) {
            limeQuery.orderBy = this.orderBy;
        }
        return limeQuery;
    }
    checkVisualModeSupport() {
        if (!this.limetypes) {
            // Can't validate yet, assume all is good
            return {
                valid: true,
                visualModeSupported: true,
                validationErrors: [],
                visualModeLimitations: [],
            };
        }
        // When in code mode, validate the parsed code value instead of current state
        let queryToCheck;
        if (this.mode === 'code' && this.codeValue) {
            try {
                queryToCheck = JSON.parse(this.codeValue);
            }
            catch (_a) {
                return {
                    valid: false,
                    visualModeSupported: false,
                    validationErrors: ['Invalid JSON'],
                    visualModeLimitations: [],
                };
            }
        }
        else {
            // Build query from current visual state
            if (!this.limetype) {
                return {
                    valid: true,
                    visualModeSupported: true,
                    validationErrors: [],
                    visualModeLimitations: [],
                };
            }
            const responseFormat = this
                .internalResponseFormat || {
                object: {
                    _id: null,
                },
            };
            queryToCheck = {
                limetype: this.limetype,
                responseFormat: responseFormat,
                filter: this.filter,
            };
            if (this.limit !== undefined && this.limit > 0) {
                queryToCheck.limit = this.limit;
            }
        }
        return isLimeQuerySupported(queryToCheck, this.limetypes, this.activeLimetype, this.visualModeEnabled);
    }
    renderModeSwitch(support) {
        const visualDisabled = !support.visualModeSupported;
        const buttons = this.getButtons().map((button) => (Object.assign(Object.assign({}, button), { selected: button.id === this.mode })));
        return (h("limel-button-group", { slot: "actions", onChange: this.handleChange, value: buttons, disabled: visualDisabled }));
    }
    renderCodeEditor(visualModeSupported) {
        return [
            h("limel-code-editor", { value: this.codeValue, language: "json", lineNumbers: true, fold: true, lint: true, onChange: this.handleCodeChange }),
            /* Show validation errors (invalid Lime Query) */
            !visualModeSupported.valid &&
                visualModeSupported.validationErrors.length > 0 && (h("div", { class: "validation-errors" }, h("strong", null, "Invalid Lime Query:"), h("ul", null, visualModeSupported.validationErrors.map((error) => (h("li", null, error)))))),
            /* Show visual mode limitations (only when visual mode is enabled and Lime Query is valid) */
            this.visualModeEnabled &&
                visualModeSupported.valid &&
                !visualModeSupported.visualModeSupported &&
                visualModeSupported.visualModeLimitations.length > 0 && (h("div", { class: "visual-mode-limitations" }, h("strong", null, "Cannot switch to visual mode:"), h("ul", null, visualModeSupported.visualModeLimitations.map((limitation) => (h("li", null, limitation)))))),
        ];
    }
    renderLimetypeSection() {
        return (h("limebb-limetype-field", { platform: this.platform, context: this.context, label: "Limetype", value: this.limetype, required: true, fieldName: "limetype", onChange: this.handleLimetypeChange }));
    }
    renderDescriptionSection() {
        if (!this.limetype) {
            return;
        }
        return (h("section", { class: "description" }, h("limel-input-field", { label: "Description", type: "textarea", value: this.description || '', placeholder: "Describe what data this query retrieves...", helperText: "Optional: Help AI agents and humans understand the query purpose", onChange: this.handleDescriptionChange, onBlur: this.handleDescriptionBlur })));
    }
    renderResponseFormatSection() {
        if (!this.limetype) {
            return;
        }
        return (h("section", { class: "response-format" }, h("limebb-lime-query-response-format-editor", { platform: this.platform, context: this.context, limetype: this.limetype, value: this.internalResponseFormat, onChange: this.handleResponseFormatChange })));
    }
    renderFilterSection() {
        if (!this.limetype) {
            return;
        }
        return (h("section", { class: "filter" }, h("limel-header", { class: "is-narrow", heading: "Filter Conditions", icon: "-lime-filter" }), h("limebb-lime-query-filter-builder", { platform: this.platform, context: this.context, limetype: this.limetype, activeLimetype: this.activeLimetype, expression: this.filter, onExpressionChange: this.handleFilterChange })));
    }
    renderQueryOptionsSection() {
        var _a;
        if (!this.limetype) {
            return;
        }
        return (h("section", { class: "query-options" }, h("limel-header", { class: "is-narrow", heading: "Query Options", icon: "ask_question" }), h("div", { class: "query-options-controls" }, h("limel-input-field", { label: "Limit", type: "number", value: ((_a = this.limit) === null || _a === void 0 ? void 0 : _a.toString()) || '', placeholder: "No limit", helperText: "Maximum number of results", onChange: this.handleLimitChange }), h("limebb-lime-query-order-by-editor", { platform: this.platform, context: this.context, limetype: this.limetype, value: this.orderBy, onChange: this.handleOrderByChange }))));
    }
    renderVisualMode() {
        return (h("div", { class: "visual-mode" }, this.renderLimetypeSection(), this.renderDescriptionSection(), this.renderResponseFormatSection(), this.renderFilterSection(), this.renderQueryOptionsSection()));
    }
    renderHeader() {
        const visualModeSupported = this.checkVisualModeSupport();
        return (h("limel-header", { heading: this.label }, this.renderModeControls(visualModeSupported)));
    }
    renderModeControls(support) {
        if (!this.visualModeEnabled) {
            return;
        }
        return this.renderModeSwitch(support);
    }
    renderCodeMode(support) {
        return h("div", { class: "code-mode" }, this.renderCodeEditor(support));
    }
};
__decorate([
    Le()
], LimeQueryBuilder.prototype, "limetypes", void 0);
LimeQueryBuilder.style = limeQueryBuilderCss();

export { LimeQueryBuilder as limebb_lime_query_builder };
