'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Sparkles, X, Loader2, Check, ChevronDown, ChevronUp, AlertTriangle, Wand2, FileText, Search, Accessibility, ArrowRight, } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../../lib/api.js';
import { adminPortalContainer } from '../../lib/portal-container.js';
const ALL_STEPS = [
    {
        key: 'structure',
        label: 'Structure',
        icon: _jsx(Wand2, { size: 14 }),
        description: 'Generate page layout and block placement',
    },
    {
        key: 'content',
        label: 'Content',
        icon: _jsx(FileText, { size: 14 }),
        description: 'Write compelling copy for every block',
    },
    {
        key: 'seo',
        label: 'SEO',
        icon: _jsx(Search, { size: 14 }),
        description: 'Optimize headings, meta tags, and keywords',
    },
    {
        key: 'accessibility',
        label: 'Accessibility',
        icon: _jsx(Accessibility, { size: 14 }),
        description: 'Fix heading hierarchy, alt text, and ARIA',
    },
];
const TONES = [
    { value: 'professional', label: 'Professional' },
    { value: 'casual', label: 'Casual' },
    { value: 'friendly', label: 'Friendly' },
    { value: 'technical', label: 'Technical' },
    { value: 'luxury', label: 'Luxury' },
];
export function AIGenerateDialog({ open, onClose, onAccept }) {
    const [phase, setPhase] = useState('prompt');
    const [prompt, setPrompt] = useState('');
    const [tone, setTone] = useState('professional');
    const [enabledSteps, setEnabledSteps] = useState(new Set(['structure', 'content', 'seo', 'accessibility']));
    const [showContext, setShowContext] = useState(false);
    const [businessName, setBusiness] = useState('');
    const [industry, setIndustry] = useState('');
    const [phone, setPhone] = useState('');
    const [address, setAddress] = useState('');
    const [services, setServices] = useState('');
    const [currentStep, setCurrentStep] = useState('');
    const [completedSteps, setCompletedSteps] = useState([]);
    const [stepMessage, setStepMessage] = useState('');
    const [result, setResult] = useState(null);
    const [error, setError] = useState(null);
    const [expandedStep, setExpandedStep] = useState(null);
    const toggleStep = (step) => {
        const next = new Set(enabledSteps);
        if (step === 'structure')
            return;
        if (next.has(step)) {
            next.delete(step);
        }
        else {
            next.add(step);
        }
        setEnabledSteps(next);
    };
    const resetState = useCallback(() => {
        setPhase('prompt');
        setPrompt('');
        setTone('professional');
        setEnabledSteps(new Set(['structure', 'content', 'seo', 'accessibility']));
        setShowContext(false);
        setBusiness('');
        setIndustry('');
        setPhone('');
        setAddress('');
        setServices('');
        setCurrentStep('');
        setCompletedSteps([]);
        setStepMessage('');
        setResult(null);
        setError(null);
        setExpandedStep(null);
    }, []);
    const handleClose = useCallback(() => {
        resetState();
        onClose();
    }, [resetState, onClose]);
    const handleGenerate = useCallback(async () => {
        if (!prompt.trim()) {
            toast.error('Please describe the page you want to create');
            return;
        }
        setPhase('generating');
        setError(null);
        const steps = ALL_STEPS.filter((s) => enabledSteps.has(s.key)).map((s) => s.key);
        setCurrentStep(steps[0]);
        setStepMessage('Starting generation...');
        const context = {};
        if (businessName)
            context.businessName = businessName;
        if (industry)
            context.industry = industry;
        if (phone)
            context.phone = phone;
        if (address)
            context.address = address;
        if (services)
            context.services = services
                .split(',')
                .map((s) => s.trim())
                .filter(Boolean);
        try {
            const res = await cmsApi('/page-builder/generate', {
                method: 'POST',
                body: JSON.stringify({
                    prompt: prompt.trim(),
                    steps,
                    tone,
                    context: Object.keys(context).length > 0 ? context : undefined,
                }),
            });
            if (res.error) {
                setError(res.error);
                setPhase('prompt');
                return;
            }
            if (res.data) {
                setResult(res.data);
                setCompletedSteps(res.data.steps.map((s) => s.step));
                setPhase('review');
            }
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Generation failed');
            setPhase('prompt');
        }
    }, [prompt, tone, enabledSteps, businessName, industry, phone, address, services]);
    const handleAccept = useCallback(() => {
        if (result?.tree) {
            onAccept(result.tree);
            toast.success('AI-generated page applied');
            handleClose();
        }
    }, [result, onAccept, handleClose]);
    return (_jsx(Dialog.Root, { open: open, onOpenChange: (next) => !next && handleClose(), children: _jsxs(Dialog.Portal, { container: adminPortalContainer(), children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-50 bg-black/50" }), _jsxs(Dialog.Content, { className: "bg-card border-border text-card-foreground fixed top-1/2 left-1/2 z-50 flex max-h-[85vh] w-[calc(100%-2rem)] max-w-2xl -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border shadow-2xl focus:outline-none", children: [_jsxs("div", { className: "border-border flex items-center justify-between border-b px-6 py-4", children: [_jsxs("div", { className: "flex items-center gap-2.5", children: [_jsx("div", { className: "bg-primary/10 rounded-lg p-1.5", children: _jsx(Sparkles, { size: 18, className: "text-primary", "aria-hidden": true }) }), _jsxs("div", { children: [_jsx(Dialog.Title, { className: "text-foreground text-base font-medium", children: "AI Page Generator" }), _jsx(Dialog.Description, { className: "text-muted-foreground text-xs", children: "Describe your page and let AI build it" })] })] }), _jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", className: "hover:bg-muted text-muted-foreground hover:text-foreground focus-visible:ring-ring rounded-md p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none", "aria-label": "Close AI page generator", children: _jsx(X, { size: 16, "aria-hidden": true }) }) })] }), _jsxs("div", { className: "flex-1 overflow-y-auto p-6", children: [phase === 'prompt' && (_jsxs("div", { className: "space-y-5", children: [error && (_jsxs("div", { className: "bg-destructive/5 border-destructive/20 flex items-start gap-2.5 rounded-lg border p-3", children: [_jsx(AlertTriangle, { size: 16, className: "text-destructive mt-0.5 shrink-0" }), _jsx("p", { className: "text-destructive text-sm", children: error })] })), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1.5 block text-sm font-medium", children: "Describe your page" }), _jsx("textarea", { value: prompt, onChange: (e) => setPrompt(e.target.value), placeholder: "e.g. A landing page for a plumbing company with a hero section, service cards, testimonials, and a contact form", rows: 4, className: "bg-background border-border focus:ring-primary/40 text-foreground placeholder:text-muted-foreground w-full resize-none rounded-lg border px-3 py-2.5 text-sm focus:ring-2 focus:outline-none", autoFocus: true })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1.5 block text-sm font-medium", children: "Tone" }), _jsx("div", { className: "flex flex-wrap gap-2", children: TONES.map((t) => (_jsx("button", { onClick: () => setTone(t.value), className: `rounded-full border px-3 py-1.5 text-xs transition-colors ${tone === t.value
                                                            ? 'border-primary bg-primary/10 text-primary'
                                                            : 'border-border bg-background text-muted-foreground hover:border-primary/40'}`, children: t.label }, t.value))) })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1.5 block text-sm font-medium", children: "Generation steps" }), _jsx("div", { className: "space-y-1.5", children: ALL_STEPS.map((step) => (_jsxs("label", { className: `flex cursor-pointer items-center gap-3 rounded-lg border p-2.5 transition-colors ${enabledSteps.has(step.key)
                                                            ? 'border-primary/30 bg-primary/5'
                                                            : 'border-border bg-background'} ${step.key === 'structure' ? 'cursor-not-allowed opacity-70' : 'hover:border-primary/20'}`, children: [_jsx("input", { type: "checkbox", checked: enabledSteps.has(step.key), onChange: () => toggleStep(step.key), disabled: step.key === 'structure', className: "sr-only" }), _jsx("div", { className: `flex h-5 w-5 shrink-0 items-center justify-center rounded ${enabledSteps.has(step.key)
                                                                    ? 'bg-primary text-primary-foreground'
                                                                    : 'bg-muted border-border border'}`, children: enabledSteps.has(step.key) && _jsx(Check, { size: 12 }) }), _jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2", children: [_jsx("span", { className: "text-muted-foreground", children: step.icon }), _jsxs("div", { children: [_jsx("span", { className: "text-foreground text-sm", children: step.label }), _jsx("span", { className: "text-muted-foreground ml-2 text-xs", children: step.description })] })] })] }, step.key))) })] }), _jsxs("div", { children: [_jsxs("button", { onClick: () => setShowContext(!showContext), className: "text-muted-foreground hover:text-foreground flex items-center gap-1.5 text-sm transition-colors", children: [showContext ? _jsx(ChevronUp, { size: 14 }) : _jsx(ChevronDown, { size: 14 }), "Business context (optional)"] }), showContext && (_jsxs("div", { className: "bg-muted/50 border-border mt-3 space-y-3 rounded-lg border p-4", children: [_jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-xs", children: "Business name" }), _jsx("input", { type: "text", value: businessName, onChange: (e) => setBusiness(e.target.value), className: "bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-xs", children: "Industry" }), _jsx("input", { type: "text", value: industry, onChange: (e) => setIndustry(e.target.value), className: "bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-xs", children: "Phone" }), _jsx("input", { type: "text", value: phone, onChange: (e) => setPhone(e.target.value), className: "bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-xs", children: "Address" }), _jsx("input", { type: "text", value: address, onChange: (e) => setAddress(e.target.value), className: "bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none" })] })] }), _jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-xs", children: "Services (comma-separated)" }), _jsx("input", { type: "text", value: services, onChange: (e) => setServices(e.target.value), placeholder: "e.g. Web design, SEO, Content marketing", className: "bg-background border-border focus:ring-primary/40 text-foreground placeholder:text-muted-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none" })] })] }))] })] })), phase === 'generating' && (_jsxs("div", { className: "space-y-6 py-8", children: [_jsxs("div", { className: "text-center", children: [_jsx(Loader2, { size: 32, className: "text-primary mx-auto mb-3 animate-spin" }), _jsx("p", { className: "text-foreground text-sm font-medium", children: stepMessage || 'Generating...' }), _jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: "This may take 15-30 seconds" })] }), _jsx("div", { className: "space-y-2", children: ALL_STEPS.filter((s) => enabledSteps.has(s.key)).map((step) => {
                                                const isComplete = completedSteps.includes(step.key);
                                                const isCurrent = currentStep === step.key;
                                                return (_jsxs("div", { className: `flex items-center gap-3 rounded-lg border p-3 transition-colors ${isComplete
                                                        ? 'border-primary/30 bg-primary/5'
                                                        : isCurrent
                                                            ? 'border-primary/50 bg-primary/10'
                                                            : 'border-border bg-muted/30'}`, children: [_jsx("div", { className: "flex h-6 w-6 shrink-0 items-center justify-center rounded-full", children: isComplete ? (_jsx("div", { className: "bg-primary flex h-6 w-6 items-center justify-center rounded-full", children: _jsx(Check, { size: 12, className: "text-primary-foreground" }) })) : isCurrent ? (_jsx(Loader2, { size: 16, className: "text-primary animate-spin" })) : (_jsx("div", { className: "bg-muted border-border h-6 w-6 rounded-full border" })) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-muted-foreground", children: step.icon }), _jsx("span", { className: `text-sm ${isCurrent || isComplete ? 'text-foreground' : 'text-muted-foreground'}`, children: step.label })] })] }, step.key));
                                            }) })] })), phase === 'review' && result && (_jsxs("div", { className: "space-y-5", children: [_jsxs("div", { className: "bg-primary/5 border-primary/20 flex items-center gap-3 rounded-lg border p-4", children: [_jsx("div", { className: "bg-primary/10 flex h-10 w-10 shrink-0 items-center justify-center rounded-full", children: _jsx(Sparkles, { size: 18, className: "text-primary" }) }), _jsxs("div", { children: [_jsx("p", { className: "text-foreground text-sm font-medium", children: "Page generated successfully" }), _jsxs("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [result.totalTokensUsed.toLocaleString(), " tokens", ' \u00B7 ', (result.totalDurationMs / 1000).toFixed(1), "s", ' \u00B7 ', result.steps.length, " step", result.steps.length !== 1 ? 's' : ''] })] })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("h3", { className: "text-foreground text-sm font-medium", children: "Generation steps" }), result.steps.map((step) => {
                                                    const info = ALL_STEPS.find((s) => s.key === step.step);
                                                    const isExpanded = expandedStep === step.step;
                                                    return (_jsxs("div", { className: "border-border overflow-hidden rounded-lg border", children: [_jsxs("button", { onClick: () => setExpandedStep(isExpanded ? null : step.step), className: "hover:bg-muted/50 flex w-full items-center gap-3 p-3 text-left transition-colors", children: [_jsx("div", { className: "bg-primary flex h-6 w-6 shrink-0 items-center justify-center rounded-full", children: _jsx(Check, { size: 12, className: "text-primary-foreground" }) }), _jsx("span", { className: "text-muted-foreground", children: info?.icon }), _jsx("span", { className: "text-foreground flex-1 text-sm", children: info?.label }), _jsxs("span", { className: "text-muted-foreground text-xs", children: [(step.metadata.durationMs / 1000).toFixed(1), "s"] }), isExpanded ? (_jsx(ChevronUp, { size: 14, className: "text-muted-foreground" })) : (_jsx(ChevronDown, { size: 14, className: "text-muted-foreground" }))] }), isExpanded && (_jsxs("div", { className: "border-border border-t px-3 pt-2 pb-3", children: [_jsx("ul", { className: "space-y-1", children: step.metadata.changes.map((change, i) => (_jsxs("li", { className: "text-muted-foreground flex items-start gap-2 text-xs", children: [_jsx(ArrowRight, { size: 10, className: "mt-0.5 shrink-0" }), change] }, i))) }), _jsxs("p", { className: "text-muted-foreground mt-2 text-xs", children: ["Tokens: ", step.metadata.tokensUsed.toLocaleString()] })] }))] }, step.step));
                                                })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Review the generated page in the canvas after accepting. You can always undo to revert." })] }))] }), _jsxs("div", { className: "border-border flex items-center justify-end gap-3 border-t px-6 py-4", children: [phase === 'prompt' && (_jsxs(_Fragment, { children: [_jsx("button", { onClick: handleClose, className: "text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors", children: "Cancel" }), _jsxs("button", { onClick: handleGenerate, disabled: !prompt.trim(), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50", children: [_jsx(Sparkles, { size: 14 }), "Generate Page"] })] })), phase === 'generating' && (_jsx("button", { onClick: handleClose, className: "text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors", children: "Cancel" })), phase === 'review' && (_jsxs(_Fragment, { children: [_jsx("button", { onClick: () => {
                                                setPhase('prompt');
                                                setResult(null);
                                            }, className: "text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors", children: "Regenerate" }), _jsxs("button", { onClick: handleAccept, className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors", children: [_jsx(Check, { size: 14 }), "Accept & Apply"] })] }))] })] })] }) }));
}
//# sourceMappingURL=AIGenerateDialog.js.map