import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { NiceTextInput as Tt, NiceSlider as so, NiceButton as We, NiceTextArea as Os, NiceSelect as fn, NiceColorPicker as Rn } from '../packages/ui/dist/index.js';
import { useNiceTranslation } from '../core/i18n.js';
import NiceAnimatedPerson from './AnimatedPerson.js';
import { DEFAULT_CHARACTER, VARIANTS } from './characterTypes.js';

const STORAGE_KEY = "nice2dev.animation-editor.character";
/* ---------- helpers ---------- */
function clampPalette(colors) {
    const c = (colors || []).slice(0, 3);
    if (c.length === 0)
        c.push("var(--anim-default-black, #000000)");
    while (c.length < 3)
        c.push(c[c.length - 1]);
    return c;
}
function ColorInputs({ value, onChange, }) {
    var _a;
    const base = clampPalette(value);
    const count = Math.min(3, Math.max(1, (_a = value === null || value === void 0 ? void 0 : value.length) !== null && _a !== void 0 ? _a : 1));
    const view = base.slice(0, count);
    return (jsxs("div", { className: "ntd-ae-color-inputs", children: [jsx("div", { className: "ntd-ae-colors", children: view.map((col, i) => (jsxs("label", { className: "ntd-ae-color-label", children: ["C", i + 1, jsx(Rn, { value: col, onChange: (color) => {
                                const next = [...view];
                                next[i] = color;
                                onChange(next);
                            } })] }, i))) }), jsxs("div", { className: "ntd-ae-color-btns", children: [jsx(We, { variant: "ghost", size: "sm", disabled: count <= 1, onClick: () => onChange(view.slice(0, Math.max(1, count - 1))), children: "-" }), jsx(We, { variant: "ghost", size: "sm", disabled: count >= 3, onClick: () => onChange([...view, view[view.length - 1] || "var(--anim-default-black, #000000)"]), children: "+" })] })] }));
}
function Row({ title, children }) {
    return (jsxs("div", { className: "ntd-ae-row", children: [jsx("div", { className: "ntd-ae-row-title", children: title }), jsx("div", { className: "ntd-ae-row-content", children: children })] }));
}
function FeatureEditor({ title, feature, variants, onChange, }) {
    const options = variants.map((v) => ({ value: v, label: v }));
    return (jsxs(Row, { title: title, children: [jsx(fn, { className: "ntd-ae-select", value: feature.variant, onChange: (val) => onChange({ ...feature, variant: val }), options: options }), jsx(ColorInputs, { value: feature.colors, onChange: (colors) => onChange({ ...feature, colors }) })] }));
}
/* ---------- component ---------- */
function NiceAnimationEditor({ initialConfig, onChange, storageKey = STORAGE_KEY, onNotify, showJsonPanel = true, showPreview = true, className, style, }) {
    var _a, _b;
    const { t } = useNiceTranslation();
    const [json, setJson] = useState("");
    const [cfg, setCfg] = useState(() => {
        if (initialConfig)
            return initialConfig;
        if (storageKey) {
            try {
                const saved = localStorage.getItem(storageKey);
                return saved ? JSON.parse(saved) : DEFAULT_CHARACTER;
            }
            catch (_a) {
                return DEFAULT_CHARACTER;
            }
        }
        return DEFAULT_CHARACTER;
    });
    useEffect(() => {
        setJson(JSON.stringify(cfg, null, 2));
        if (storageKey) {
            try {
                localStorage.setItem(storageKey, JSON.stringify(cfg));
            }
            catch ( /* ignore */_a) { /* ignore */ }
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(cfg);
    }, [cfg, storageKey, onChange]);
    const applyJson = () => {
        try {
            const parsed = JSON.parse(json);
            setCfg(parsed);
            onNotify === null || onNotify === void 0 ? void 0 : onNotify(t("characterEditor.jsonApplied", "JSON applied"), "success");
        }
        catch (_a) {
            onNotify === null || onNotify === void 0 ? void 0 : onNotify(t("characterEditor.invalidJson", "Invalid JSON"), "error");
        }
    };
    const downloadJson = () => {
        const blob = new Blob([JSON.stringify(cfg, null, 2)], { type: "application/json" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `${cfg.name || "character"}.json`;
        a.click();
        URL.revokeObjectURL(url);
    };
    const randomizeColors = () => {
        const rand = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0")}`;
        const paint = (f) => ({ ...f, colors: [rand(), rand(), rand()] });
        setCfg({
            ...cfg,
            face: paint(cfg.face),
            hair: paint(cfg.hair),
            eyes: paint(cfg.eyes),
            nose: paint(cfg.nose),
            mouth: paint(cfg.mouth),
            outfit: paint(cfg.outfit),
            headwear: paint(cfg.headwear),
            prop: paint(cfg.prop),
        });
    };
    const updateFeature = (key, val) => {
        setCfg((prev) => ({ ...prev, [key]: val }));
    };
    return (jsxs("div", { className: `ntd-animation-editor ${className !== null && className !== void 0 ? className : ""}`, style: style, children: [jsxs("div", { className: "ntd-ae-controls", children: [jsx(Row, { title: t("characterEditor.name", "Name"), children: jsx(Tt, { className: "ntd-ae-input", value: cfg.name || "", onChange: (val) => setCfg({ ...cfg, name: val }), placeholder: t("characterEditor.namePlaceholder", "Character name") }) }), jsxs(Row, { title: t("characters.size", "Size"), children: [jsx(so, { min: 140, max: 300, value: (_a = cfg.size) !== null && _a !== void 0 ? _a : 180, onChange: (val) => setCfg({ ...cfg, size: val }) }), jsxs("span", { className: "ntd-ae-size-value", children: [(_b = cfg.size) !== null && _b !== void 0 ? _b : 180, "px"] })] }), jsx(FeatureEditor, { title: t("characters.faceShape", "Face"), feature: cfg.face, variants: VARIANTS.face, onChange: (v) => updateFeature("face", v) }), jsx(FeatureEditor, { title: t("characters.hairstyle", "Hair"), feature: cfg.hair, variants: VARIANTS.hair, onChange: (v) => updateFeature("hair", v) }), jsx(FeatureEditor, { title: t("characters.eyes", "Eyes"), feature: cfg.eyes, variants: VARIANTS.eyes, onChange: (v) => updateFeature("eyes", v) }), jsx(FeatureEditor, { title: t("characters.nose", "Nose"), feature: cfg.nose, variants: VARIANTS.nose, onChange: (v) => updateFeature("nose", v) }), jsx(FeatureEditor, { title: t("characters.mouth", "Mouth"), feature: cfg.mouth, variants: VARIANTS.mouth, onChange: (v) => updateFeature("mouth", v) }), jsx(FeatureEditor, { title: t("characters.clothing", "Outfit"), feature: cfg.outfit, variants: VARIANTS.outfit, onChange: (v) => updateFeature("outfit", v) }), jsx(FeatureEditor, { title: t("characters.headwear", "Headwear"), feature: cfg.headwear, variants: VARIANTS.headwear, onChange: (v) => updateFeature("headwear", v) }), jsx(FeatureEditor, { title: t("characters.prop", "Prop"), feature: cfg.prop, variants: VARIANTS.prop, onChange: (v) => updateFeature("prop", v) }), jsxs("div", { className: "ntd-ae-action-row", children: [jsxs(We, { className: "ntd-ae-btn", variant: "ghost", onClick: randomizeColors, children: ["\uD83C\uDFB2 ", t("characterEditor.randomizeColors", "Randomize colors")] }), jsxs(We, { className: "ntd-ae-btn", variant: "ghost", onClick: downloadJson, children: ["\u2B07 ", t("characters.downloadJson", "Download JSON")] })] }), showJsonPanel && (jsxs("div", { className: "ntd-ae-json-panel", children: [jsx("div", { className: "ntd-ae-json-label", children: t("characterEditor.jsonSection", "JSON") }), jsx(Os, { className: "ntd-ae-textarea", value: json, onChange: (val) => setJson(val) }), jsxs("div", { className: "ntd-ae-json-actions", children: [jsx(We, { className: "ntd-ae-btn", variant: "primary", onClick: applyJson, children: t("characterEditor.applyJson", "Apply JSON") }), jsx(We, { className: "ntd-ae-btn", variant: "ghost", onClick: () => navigator.clipboard.writeText(JSON.stringify(cfg, null, 2)), children: t("characterEditor.copyToClipboard", "Copy") })] })] }))] }), showPreview && (jsxs("div", { className: "ntd-ae-preview", children: [jsx("div", { className: "ntd-ae-preview-label", children: t("characterEditor.preview", "Preview") }), jsx(NiceAnimatedPerson, { character: cfg, score: 10, startPose: "idle" })] }))] }));
}
/** @deprecated Use NiceAnimationEditor */
const AnimationEditor = NiceAnimationEditor;

export { AnimationEditor, NiceAnimationEditor };
//# sourceMappingURL=AnimationEditor.js.map
