"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaPopup = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const uikit_1 = require("@gravity-ui/uikit");
const cn_1 = require("../../utils/cn.js");
const parseSchema_1 = require("../../utils/parseSchema.js");
const b = (0, cn_1.formBuilderV2Cn)('schema-popup');
const stringify = (schema) => JSON.stringify(schema, null, 2);
const SchemaPopup = ({ schema, onApply, open, onOpenChange, anchorElement, }) => {
    const textareaRef = React.useRef(null);
    const copyTimeoutRef = React.useRef(null);
    const [draft, setDraft] = React.useState(() => stringify(schema));
    const [error, setError] = React.useState(null);
    const [copied, setCopied] = React.useState(false);
    const [isFocused, setIsFocused] = React.useState(false);
    React.useEffect(() => {
        if (!isFocused) {
            setDraft(stringify(schema));
            setError(null);
        }
    }, [schema, isFocused]);
    React.useEffect(() => () => {
        if (copyTimeoutRef.current)
            clearTimeout(copyTimeoutRef.current);
    }, []);
    const applyDraft = (value) => {
        setDraft(value);
        const result = (0, parseSchema_1.parseSchema)(value);
        if (result.ok) {
            setError(null);
            onApply(result.fields);
        }
        else {
            setError(result.error);
        }
    };
    const replaceSelection = (insert, caretOffset) => {
        const t = textareaRef.current;
        if (!t)
            return;
        const { selectionStart, selectionEnd } = t;
        const next = draft.slice(0, selectionStart) + insert + draft.slice(selectionEnd);
        const nextCaret = selectionStart + caretOffset;
        applyDraft(next);
        requestAnimationFrame(() => {
            t.selectionStart = nextCaret;
            t.selectionEnd = nextCaret;
        });
    };
    const handleKeyDown = (event) => {
        if (event.key === 'Tab') {
            event.preventDefault();
            replaceSelection('  ', 2);
            return;
        }
        if (event.key === 'Enter') {
            event.preventDefault();
            const t = event.currentTarget;
            const before = draft.slice(0, t.selectionStart);
            const lineStart = before.lastIndexOf('\n') + 1;
            const indent = before.slice(lineStart).match(/^[ \t]*/)?.[0] ?? '';
            const insert = `\n${indent}`;
            replaceSelection(insert, insert.length);
        }
    };
    const handleCopy = React.useCallback(async () => {
        try {
            await navigator.clipboard.writeText(draft);
            setCopied(true);
            if (copyTimeoutRef.current)
                clearTimeout(copyTimeoutRef.current);
            copyTimeoutRef.current = setTimeout(() => setCopied(false), 1500);
        }
        catch { }
    }, [draft]);
    return ((0, jsx_runtime_1.jsx)(uikit_1.Popup, { anchorElement: anchorElement, open: open, onOpenChange: onOpenChange, placement: "bottom-end", children: (0, jsx_runtime_1.jsxs)(uikit_1.Card, { className: b(), view: "outlined", children: [(0, jsx_runtime_1.jsxs)("div", { className: b('header'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Text, { variant: "subheader-2", children: "Form schema" }), (0, jsx_runtime_1.jsx)(uikit_1.Text, { variant: "caption-1", color: "hint", children: "Edit JSON directly \u2014 the canvas updates live. Paste your own schema to load it. Selection on canvas resets after each edit." })] }), (0, jsx_runtime_1.jsx)("textarea", { ref: textareaRef, className: b('textarea', { error: Boolean(error) }), value: draft, onChange: (event) => applyDraft(event.target.value), onKeyDown: handleKeyDown, onFocus: () => setIsFocused(true), onBlur: () => setIsFocused(false), spellCheck: false, wrap: "off" }), error && ((0, jsx_runtime_1.jsx)("div", { className: b('error-message'), children: (0, jsx_runtime_1.jsx)(uikit_1.Text, { variant: "caption-1", color: "danger", children: error }) })), (0, jsx_runtime_1.jsxs)("div", { className: b('actions'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Button, { view: "action", size: "m", onClick: handleCopy, children: copied ? '✓ Copied' : 'Copy' }), (0, jsx_runtime_1.jsx)(uikit_1.Button, { view: "flat", size: "m", onClick: () => onOpenChange(false), children: "Close" })] })] }) }));
};
exports.SchemaPopup = SchemaPopup;
//# sourceMappingURL=SchemaPopup.js.map
