"use strict"; 
const { registerPlugin } = wp.plugins;

const PluginDocumentSettingPanel =
    wp.blockEditor?.PluginDocumentSettingPanel ||
    wp.editor?.PluginDocumentSettingPanel ||
    wp.editPost?.PluginDocumentSettingPanel;
const { useState } = wp.element;
const { useDispatch } = wp.data;

const AiMetaGenerator = () => {
    const { editPost } = useDispatch('core/editor');
    const { TextControl, TextareaControl, Button, SelectControl } = wp.components;
    const firstModel = Object.keys(aiMeta.models || {})[0] || '';
    const [model, setModel] = useState(firstModel);
    const modelOptions = Object.entries(aiMeta.models || {}).map(([value, label]) => ({
        label: label,
        value: value
    }));
    const [metaKey, setMetaKey] = useState('');
    const [prompt, setPrompt] = useState('');
    const [loading, setLoading] = useState(false);
    const generate = async () => {
        if (!metaKey || !prompt) return;

        setLoading(true);

        try {
            const postId = wp.data.select('core/editor').getCurrentPostId();

            const res = await fetch(aiMeta.ajax_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    action: 'ai_meta_generate',
                    nonce: aiMeta.nonce,
                    prompt: prompt,
                    model: model,
                    meta_key: metaKey,
                    post_id: postId
                })
            });

            const text = await res.text();

            let data;
            try {
                data = JSON.parse(text);
            } catch (e) {
                alert('Invalid server response (not JSON)');
                setLoading(false);
                return;
            }

            if (!data.success) {
                const msg = data?.data?.message || 'Unknown error';
                alert('AI Error: ' + msg);
                setLoading(false);
                return;
            }

            setTimeout(() => {
                window.location.reload();
            }, 300);

            console.log('AI Generation Result:', data.data.result);
        } catch (err) {
            console.error('Request failed:', err);
            alert('Request failed: ' + err.message);
        }

        setLoading(false);
    };

    return wp.element.createElement(
        PluginDocumentSettingPanel,
        {
            name: 'ai-meta-generator',
            title: 'AI Custom Field Generator',
            icon: null
        },
        wp.element.createElement(TextControl, {
            label: 'Meta Key',
            value: metaKey,
            placeholder: 'e.g. sabias_que',
            onChange: setMetaKey
        }),
        wp.element.createElement(TextareaControl, {
            label: 'Prompt',
            value: prompt,
            placeholder: 'Write prompt, you can use %%post_title%% etc...',
            onChange: setPrompt
        }),
        wp.element.createElement(SelectControl, {
            label: 'Model',
            value: model,
            options: modelOptions,
            onChange: setModel
        }),
        wp.element.createElement(Button, {
            isPrimary: true,
            onClick: generate,
            disabled: loading
        }, loading ? 'Generating...' : 'Generate')
    );
};

registerPlugin('ai-meta-generator', {
    render: AiMetaGenerator
});