var __decorate = (this && this.__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;
};
import { h } from "@stencil/core";
import { SelectLimeTypes as Limetypes, } from "@limetech/lime-web-components";
import { parseResponseFormat, stringifyResponseFormat, getDefaultResponseFormat, } from "./response-format/response-format-helpers";
import { validateResponseFormatOnly, } from "./lime-query-validation";
/**
 * Response Format Builder
 *
 * A focused component for editing Lime Query ResponseFormat in isolation.
 * Supports both visual and code modes for maximum flexibility.
 *
 * Use this component when you need to configure which properties to return
 * from a query, but don't need filter, limit, or other query parameters.
 *
 * **Features**:
 * - **Visual Mode**: Visual property selector with relation navigation
 * - **Code Mode**: JSON editor for ResponseFormat structure
 * - **Validation**: Ensures JSON is valid ResponseFormat (rejects other fields)
 * - **Mode Toggle**: Switch between visual and code modes seamlessly
 * - **Feature Flag**: Respects `useLimeQueryBuilderGuiMode` setting
 *
 * @example
 * ```tsx
 * <limebb-lime-query-response-format-builder
 *     platform={this.platform}
 *     context={this.context}
 *     limetype="deal"
 *     value={this.responseFormat}
 *     label="Select Properties to Return"
 *     onChange={this.handleChange}
 * />
 * ```
 *
 * @exampleComponent limebb-example-response-format-builder-basic
 * @private
 */
export class LimeQueryResponseFormatBuilder {
    constructor() {
        /**
         * Optional label for the builder
         */
        this.label = 'Response Format';
        /**
         * Optional helper text for the builder
         */
        this.helperText = '';
        this.mode = 'visual';
        this.codeValue = '';
        this.handleModeChange = (event) => {
            event.stopPropagation();
            const mode = event.detail.id;
            if (mode === 'visual') {
                this.switchToVisualMode();
            }
            else if (mode === 'code') {
                this.switchToCode();
            }
        };
        /**
         * Switch from code mode to visual mode
         */
        this.switchToVisualMode = () => {
            // Validate JSON before switching
            try {
                const parsed = parseResponseFormat(this.codeValue);
                // Check if it's supported in visual mode
                const support = validateResponseFormatOnly(parsed, this.limetypes, this.limetype, this.visualModeEnabled);
                if (!support.visualModeSupported) {
                    // Don't switch if visual mode can't render this response format
                    return;
                }
                // Update internal state from parsed value
                this.internalValue = parsed;
                this.mode = 'visual';
                this.change.emit(parsed);
            }
            catch (_a) {
                // Don't switch if JSON is invalid (linter will show the error)
            }
        };
        /**
         * Switch from visual mode to code mode
         */
        this.switchToCode = () => {
            this.updateCodeValue();
            this.mode = 'code';
        };
        /**
         * Handle code editor changes
         * @param event
         */
        this.handleCodeChange = (event) => {
            event.stopPropagation();
            this.codeValue = event.detail;
            // Try to parse and emit if valid
            try {
                const parsed = parseResponseFormat(this.codeValue);
                this.internalValue = parsed;
                this.change.emit(parsed);
            }
            catch (_a) {
                // Invalid JSON - don't emit change
                // Validation errors will be shown by checkVisualModeSupport()
            }
        };
        /**
         * Handle visual mode changes
         * @param event
         */
        this.handleVisualModeChange = (event) => {
            event.stopPropagation();
            this.internalValue = event.detail;
            this.updateCodeValue();
            this.change.emit(event.detail);
        };
    }
    /**
     * Check if visual mode is enabled via feature flag
     */
    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() {
        // Initialize internal value
        this.internalValue = this.value || getDefaultResponseFormat();
        // Update code value from internal value
        this.updateCodeValue();
        // Force code mode if visual mode is disabled
        if (!this.visualModeEnabled) {
            this.mode = 'code';
            return;
        }
        // Check if visual mode is supported for current value
        const support = this.checkVisualModeSupport();
        if (!support.visualModeSupported) {
            this.mode = 'code';
        }
    }
    componentWillUpdate() {
        // Sync internal value when prop changes externally
        if (this.value && this.mode === 'visual') {
            this.internalValue = this.value;
        }
    }
    render() {
        const visualModeSupported = this.checkVisualModeSupport();
        return (h("div", { key: '65a41f46fe1088f0d52be0337c427177a1aa1a44', class: "response-format-builder" }, this.label && h("h1", { key: '5a75e321aee3ff6753baccbd72d17c5377f28d28', class: "builder-label" }, this.label), this.helperText && (h("p", { key: 'e13518253b52ff8f847575b4465dc2295c7452f0', class: "builder-helper-text" }, this.helperText)), this.visualModeEnabled && (h("div", { key: '2122357f51fd2185d1b544381eb2199de5b1f56c', class: "mode-controls" }, this.renderModeSwitch(visualModeSupported))), !this.visualModeEnabled || this.mode === 'code' ? (h("div", { class: "code-mode" }, this.renderCodeEditor(visualModeSupported))) : (h("div", { class: "visual-mode" }, this.renderVisualMode()))));
    }
    renderModeSwitch(support) {
        const visualDisabled = !support.visualModeSupported;
        const buttons = [
            {
                id: 'visual',
                title: 'Visual',
            },
            {
                id: 'code',
                title: 'Code',
            },
        ].map((button) => (Object.assign(Object.assign({}, button), { selected: button.id === this.mode })));
        return (h("limel-button-group", { value: buttons, disabled: visualDisabled, onChange: this.handleModeChange }));
    }
    renderCodeEditor(support) {
        return (h("div", { class: "code-editor-container" }, h("limel-code-editor", { value: this.codeValue, language: "json", lineNumbers: true, fold: true, lint: true, onChange: this.handleCodeChange }), !support.valid && support.validationErrors.length > 0 && (h("div", { class: "validation-errors" }, h("strong", null, "Invalid Response Format:"), h("ul", null, support.validationErrors.map((error) => (h("li", null, error)))))), this.visualModeEnabled &&
            support.valid &&
            !support.visualModeSupported &&
            support.visualModeLimitations.length > 0 && (h("div", { class: "visual-mode-limitations" }, h("strong", null, "Cannot switch to visual mode:"), h("ul", null, support.visualModeLimitations.map((limitation) => (h("li", null, limitation))))))));
    }
    renderVisualMode() {
        return (h("limebb-lime-query-response-format-editor", { platform: this.platform, context: this.context, limetype: this.limetype, value: this.internalValue, onChange: this.handleVisualModeChange }));
    }
    /**
     * Check if current value can be rendered in visual mode
     */
    checkVisualModeSupport() {
        if (!this.limetypes) {
            return {
                valid: false,
                visualModeSupported: false,
                validationErrors: ['Limetypes not loaded'],
                visualModeLimitations: [],
            };
        }
        // Try to parse code value if in code mode
        let valueToCheck;
        if (this.mode === 'code') {
            try {
                valueToCheck = parseResponseFormat(this.codeValue);
            }
            catch (error) {
                return {
                    valid: false,
                    visualModeSupported: false,
                    validationErrors: [error.message],
                    visualModeLimitations: [],
                };
            }
        }
        else {
            valueToCheck = this.internalValue;
        }
        return validateResponseFormatOnly(valueToCheck, this.limetypes, this.limetype, this.visualModeEnabled);
    }
    /**
     * Update code value from internal state
     */
    updateCodeValue() {
        this.codeValue = stringifyResponseFormat(this.internalValue);
    }
    static get is() { return "limebb-lime-query-response-format-builder"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["lime-query-response-format-builder.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["lime-query-response-format-builder.css"]
        };
    }
    static get properties() {
        return {
            "platform": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentPlatform",
                    "resolved": "LimeWebComponentPlatform",
                    "references": {
                        "LimeWebComponentPlatform": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentPlatform",
                            "referenceLocation": "LimeWebComponentPlatform"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Platform service provider"
                },
                "getter": false,
                "setter": false
            },
            "context": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentContext",
                    "resolved": "LimeWebComponentContext",
                    "references": {
                        "LimeWebComponentContext": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentContext",
                            "referenceLocation": "LimeWebComponentContext"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Component context"
                },
                "getter": false,
                "setter": false
            },
            "limetype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The limetype to configure response format for\nThis is fixed and not editable by the user"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "limetype"
            },
            "value": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "ResponseFormat",
                    "resolved": "ResponseFormat | undefined",
                    "references": {
                        "ResponseFormat": {
                            "location": "import",
                            "path": "./lime-query.types",
                            "id": "src/components/lime-query-builder/lime-query.types.ts::ResponseFormat",
                            "referenceLocation": "ResponseFormat"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Current response format value"
                },
                "getter": false,
                "setter": false
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional label for the builder"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label",
                "defaultValue": "'Response Format'"
            },
            "helperText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional helper text for the builder"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "helper-text",
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "limetypes": {},
            "mode": {},
            "codeValue": {},
            "internalValue": {}
        };
    }
    static get events() {
        return [{
                "method": "change",
                "name": "change",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the response format changes"
                },
                "complexType": {
                    "original": "ResponseFormat",
                    "resolved": "ResponseFormat",
                    "references": {
                        "ResponseFormat": {
                            "location": "import",
                            "path": "./lime-query.types",
                            "id": "src/components/lime-query-builder/lime-query.types.ts::ResponseFormat",
                            "referenceLocation": "ResponseFormat"
                        }
                    }
                }
            }];
    }
}
__decorate([
    Limetypes()
], LimeQueryResponseFormatBuilder.prototype, "limetypes", void 0);
