"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * AI Content Generator Component
 *
 * A component for generating structured content using AI
 */
const react_1 = require("react");
const useAI_js_1 = __importDefault(require("../../hooks/useAI.js"));
const ContentGenerator = ({ templates, initialTemplateId, className = '', onContentGenerated }) => {
    // State
    const [selectedTemplateId, setSelectedTemplateId] = (0, react_1.useState)(initialTemplateId || (templates.length > 0 ? templates[0].id : ''));
    const [fieldValues, setFieldValues] = (0, react_1.useState)({});
    const [generatedContent, setGeneratedContent] = (0, react_1.useState)('');
    const [isPreviewMode, setIsPreviewMode] = (0, react_1.useState)(false);
    const [generating, setGenerating] = (0, react_1.useState)(false);
    const [estimatedTokens, setEstimatedTokens] = (0, react_1.useState)(0);
    const contentRef = (0, react_1.useRef)(null);
    // Get AI capabilities from our hook
    const { chat, isLoading, isError, error } = (0, useAI_js_1.default)({
        initialConfig: {
            model: 'claude-3-sonnet-20240229',
            temperature: 0.7
        },
        onError: (err) => {
            console.error('Generation Error:', err);
        }
    });
    // Get the selected template
    const selectedTemplate = templates.find(t => t.id === selectedTemplateId);
    // Reset field values when template changes
    (0, react_1.useEffect)(() => {
        if (selectedTemplate) {
            const defaultValues = {};
            selectedTemplate.fields.forEach(field => {
                defaultValues[field.id] = field.default || '';
            });
            setFieldValues(defaultValues);
            setGeneratedContent('');
            setIsPreviewMode(false);
        }
    }, [selectedTemplateId, selectedTemplate]);
    // Estimate tokens (very rough estimate)
    (0, react_1.useEffect)(() => {
        if (selectedTemplate) {
            // Roughly estimate 1.5 tokens per word
            const promptWords = selectedTemplate.systemPrompt.split(/\s+/).length;
            let fieldWords = 0;
            Object.values(fieldValues).forEach(value => {
                fieldWords += value.split(/\s+/).length;
            });
            // Roughly estimate total tokens
            const estimatedPromptTokens = Math.ceil(promptWords * 1.5);
            const estimatedFieldTokens = Math.ceil(fieldWords * 1.5);
            const estimatedCompletionTokens = Math.ceil((promptWords + fieldWords) * 3); // Assuming response is 2x input
            setEstimatedTokens(estimatedPromptTokens + estimatedFieldTokens + estimatedCompletionTokens);
        }
    }, [selectedTemplate, fieldValues]);
    // Handle field change
    const handleFieldChange = (fieldId, value) => {
        setFieldValues(prev => ({
            ...prev,
            [fieldId]: value
        }));
    };
    // Handle template change
    const handleTemplateChange = (e) => {
        setSelectedTemplateId(e.target.value);
    };
    // Generate content
    const generateContent = (0, react_1.useCallback)(async () => {
        if (!selectedTemplate || isLoading || generating)
            return;
        try {
            setGenerating(true);
            // Prepare user prompt from field values
            let userPrompt = "Please generate content based on the following information:\n\n";
            selectedTemplate.fields.forEach(field => {
                const value = fieldValues[field.id] || '';
                if (value) {
                    userPrompt += `${field.name}: ${value}\n`;
                }
            });
            // Add format instructions
            userPrompt += `\nPlease format the output as ${selectedTemplate.outputFormat}.`;
            // Generate content
            const response = await chat({
                messages: [
                    { role: 'system', content: selectedTemplate.systemPrompt },
                    { role: 'user', content: userPrompt }
                ],
                temperature: 0.7,
                maxTokens: 2000
            });
            // Extract the content from the response
            const content = response.response?.choices[0]?.message?.content || '';
            setGeneratedContent(content);
            // Notify parent component
            if (onContentGenerated) {
                onContentGenerated(content, selectedTemplate);
            }
            // Switch to preview mode
            setIsPreviewMode(true);
        }
        catch (err) {
            console.error('Error generating content:', err);
        }
        finally {
            setGenerating(false);
        }
    }, [selectedTemplate, fieldValues, isLoading, generating, chat, onContentGenerated]);
    // Toggle preview mode
    const togglePreviewMode = () => {
        setIsPreviewMode(prev => !prev);
    };
    // Copy content to clipboard
    const copyContent = () => {
        if (generatedContent) {
            navigator.clipboard.writeText(generatedContent)
                .then(() => {
                // Show copy success message
                const el = document.createElement('div');
                el.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-md';
                el.textContent = 'Copied to clipboard!';
                document.body.appendChild(el);
                // Remove after 2 seconds
                setTimeout(() => {
                    document.body.removeChild(el);
                }, 2000);
            })
                .catch(err => {
                console.error('Failed to copy:', err);
            });
        }
    };
    // Render Markdown content
    const renderMarkdown = (markdown) => {
        // Note: In a real implementation, you would use a Markdown renderer library
        // This is a simple placeholder implementation
        return ((0, jsx_runtime_1.jsx)("div", { className: "prose max-w-none", dangerouslySetInnerHTML: {
                __html: markdown
                    .replace(/^# (.*$)/gm, '<h1>$1</h1>')
                    .replace(/^## (.*$)/gm, '<h2>$1</h2>')
                    .replace(/^### (.*$)/gm, '<h3>$1</h3>')
                    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                    .replace(/\*(.*?)\*/g, '<em>$1</em>')
                    .replace(/\n/g, '<br />')
            } }));
    };
    // Render HTML content
    const renderHTML = (html) => {
        return ((0, jsx_runtime_1.jsx)("div", { className: "prose max-w-none", dangerouslySetInnerHTML: { __html: html } }));
    };
    // Render JSON content
    const renderJSON = (jsonString) => {
        try {
            const json = JSON.parse(jsonString);
            return ((0, jsx_runtime_1.jsx)("pre", { className: "bg-gray-50 p-4 rounded-md overflow-auto", children: (0, jsx_runtime_1.jsx)("code", { className: "text-sm", children: JSON.stringify(json, null, 2) }) }));
        }
        catch (err) {
            return ((0, jsx_runtime_1.jsxs)("div", { className: "text-red-500", children: ["Invalid JSON: ", jsonString] }));
        }
    };
    // Render text content
    const renderText = (text) => {
        return ((0, jsx_runtime_1.jsx)("pre", { className: "whitespace-pre-wrap", children: text }));
    };
    // Render content based on format
    const renderContent = (content, format) => {
        switch (format) {
            case 'markdown':
                return renderMarkdown(content);
            case 'html':
                return renderHTML(content);
            case 'json':
                return renderJSON(content);
            case 'text':
            default:
                return renderText(content);
        }
    };
    if (!selectedTemplate) {
        return ((0, jsx_runtime_1.jsx)("div", { className: `bg-white rounded-lg shadow-md p-6 ${className}`, children: (0, jsx_runtime_1.jsx)("p", { className: "text-gray-500", children: "No templates available" }) }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { className: `bg-white rounded-lg shadow-md ${className}`, children: [(0, jsx_runtime_1.jsxs)("div", { className: "p-4 border-b", children: [(0, jsx_runtime_1.jsx)("h2", { className: "text-xl font-semibold", children: "AI Content Generator" }), (0, jsx_runtime_1.jsx)("p", { className: "text-gray-500", children: "Generate structured content with AI assistance" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "p-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "mb-6", children: [(0, jsx_runtime_1.jsx)("label", { className: "block mb-2 font-medium", children: "Template" }), (0, jsx_runtime_1.jsx)("select", { value: selectedTemplateId, onChange: handleTemplateChange, className: "w-full p-2 border rounded-md", disabled: isLoading || generating, children: templates.map(template => ((0, jsx_runtime_1.jsx)("option", { value: template.id, children: template.name }, template.id))) }), (0, jsx_runtime_1.jsx)("p", { className: "mt-2 text-gray-500 text-sm", children: selectedTemplate.description })] }), isPreviewMode && generatedContent ? ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-center mb-4", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-semibold", children: "Generated Content" }), (0, jsx_runtime_1.jsxs)("div", { className: "flex space-x-2", children: [(0, jsx_runtime_1.jsx)("button", { onClick: togglePreviewMode, className: "px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300", children: "Edit" }), (0, jsx_runtime_1.jsx)("button", { onClick: copyContent, className: "px-3 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600", children: "Copy" })] })] }), (0, jsx_runtime_1.jsx)("div", { ref: contentRef, className: "p-4 border rounded-md bg-gray-50 mb-4 max-h-96 overflow-y-auto", children: renderContent(generatedContent, selectedTemplate.outputFormat) })] })) : ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-semibold mb-4", children: "Content Parameters" }), (0, jsx_runtime_1.jsx)("div", { className: "space-y-4 mb-6", children: selectedTemplate.fields.map(field => ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsxs)("label", { className: "block mb-1 font-medium", children: [field.name, field.required && (0, jsx_runtime_1.jsx)("span", { className: "text-red-500 ml-1", children: "*" })] }), field.type === 'textarea' ? ((0, jsx_runtime_1.jsx)("textarea", { value: fieldValues[field.id] || '', onChange: (e) => handleFieldChange(field.id, e.target.value), className: "w-full p-2 border rounded-md", placeholder: field.placeholder, rows: 5, disabled: isLoading || generating, required: field.required })) : field.type === 'select' ? ((0, jsx_runtime_1.jsxs)("select", { value: fieldValues[field.id] || '', onChange: (e) => handleFieldChange(field.id, e.target.value), className: "w-full p-2 border rounded-md", disabled: isLoading || generating, required: field.required, children: [(0, jsx_runtime_1.jsxs)("option", { value: "", children: ["-- Select ", field.name, " --"] }), field.options?.map(option => ((0, jsx_runtime_1.jsx)("option", { value: option, children: option }, option)))] })) : ((0, jsx_runtime_1.jsx)("input", { type: "text", value: fieldValues[field.id] || '', onChange: (e) => handleFieldChange(field.id, e.target.value), className: "w-full p-2 border rounded-md", placeholder: field.placeholder, disabled: isLoading || generating, required: field.required })), field.description && ((0, jsx_runtime_1.jsx)("p", { className: "mt-1 text-gray-500 text-sm", children: field.description }))] }, field.id))) }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-sm text-gray-500", children: ["Estimated tokens: ~", estimatedTokens] }), (0, jsx_runtime_1.jsx)("button", { onClick: generateContent, className: "px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-blue-300", disabled: isLoading ||
                                            generating ||
                                            selectedTemplate.fields.some(f => f.required && !fieldValues[f.id]), children: generating ? 'Generating...' : 'Generate Content' })] })] })), isError && error && ((0, jsx_runtime_1.jsxs)("div", { className: "mt-4 bg-red-100 text-red-800 p-3 rounded-lg", children: [(0, jsx_runtime_1.jsxs)("p", { className: "font-semibold", children: ["Error: ", error.code] }), (0, jsx_runtime_1.jsx)("p", { children: error.message })] }))] })] }));
};
exports.default = ContentGenerator;
//# sourceMappingURL=ContentGenerator.js.map