import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import { ToastContainer, toast } from "react-toastify";

const MODULE_LABELS = {
    content_steward: {
        title: "AI Content Steward",
        description: "Analyze and improve posts/pages with AI.",
        status: "Available",
    },
    pages_manager: {
        title: "Pages Manager",
        description: "WordPress page CRUD operations.",
        status: "Available",
    },
    media_manager: {
        title: "Media Manager",
        description: "Upload, update, and manage media files.",
        status: "Available",
    },
    users_manager: {
        title: "Users Manager",
        description: "Search, create, and manage WordPress users.",
        status: "Available",
    },
    cpt_manager: {
        title: "Custom Post Types Manager",
        description: "CRUD operations for custom post types.",
        status: "Available",
    },
    rest_api: {
        title: "REST API Tools",
        description: "Discover and execute REST API endpoints.",
        status: "Available",
    },
    site_info: {
        title: "Site Info & Diagnostics",
        description: "View site info, plugins, themes, and users.",
        status: "Available",
    },
    settings_manager: {
        title: "Settings Manager",
        description: "View and update WordPress site settings.",
        status: "Available",
    },
    store_manager: {
        title: "AI Store Manager (WooCommerce)",
        description: "WooCommerce products, orders & reports.",
        status: "Available (requires WooCommerce)",
    },
    support_desk: {
        title: "AI Support Desk",
        description: "Summaries & reply suggestions for comments/support.",
        status: "Coming soon",
    },
    automations: {
        title: "AI Automation Recipes / Workflows",
        description: "Rule-based AI automations and workflows.",
        status: "Coming soon",
    },
};

const NAV_ITEMS = [
    { id: "dashboard", label: "Dashboard" },
    { id: "workflows", label: "Workflows" },
    { id: "documentation", label: "Documentation" },
];

function Toggle({ checked, onChange, disabled }) {
    return (
        <button
            type="button"
            onClick={() => (!disabled ? onChange(!checked) : null)}
            className={`aah-relative aah-inline-flex aah-h-6 aah-w-11 aah-items-center aah-rounded-full ${
                checked ? "aah-bg-green-500" : "aah-bg-slate-300"
            } aah-transition ${disabled ? "aah-opacity-50 aah-cursor-not-allowed" : ""}`}
        >
      <span
          className={`aah-inline-block aah-h-5 aah-w-5 aah-transform aah-rounded-full aah-bg-white aah-shadow aah-transition ${
              checked ? "aah-translate-x-5" : "aah-translate-x-1"
          }`}
      />
        </button>
    );
}

function WorkflowsView({ abilities, loading, wpNonce, workflowsRestUrl }) {
    const [searchTerm, setSearchTerm] = useState("");
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(() => {
        const stored = localStorage.getItem("aah_workflow_page_size");
        return stored ? parseInt(stored, 10) : 10;
    });

    const [builderName, setBuilderName] = useState("");
    const [builderPrompt, setBuilderPrompt] = useState("");
    const [builderAbilities, setBuilderAbilities] = useState([]);
    const [workflows, setWorkflows] = useState([]);
    const [workflowsLoading, setWorkflowsLoading] = useState(true);
    const [savingWorkflow, setSavingWorkflow] = useState(false);
    const [editingId, setEditingId] = useState("");

    useEffect(() => {
        loadWorkflows();
    }, []);

    useEffect(() => {
        localStorage.setItem("aah_workflow_page_size", pageSize.toString());
        setPage(1);
    }, [pageSize]);

    useEffect(() => {
        if (builderAbilities.length === 0) {
            setBuilderPrompt("");
            return;
        }
        const prompt = buildWorkflowPrompt(builderAbilities, abilities);
        setBuilderPrompt(prompt);
    }, [builderAbilities, abilities]);

    const loadWorkflows = async () => {
        if (!workflowsRestUrl) return;
        try {
            setWorkflowsLoading(true);
            const res = await fetch(workflowsRestUrl, {
                headers: {
                    "X-WP-Nonce": wpNonce,
                },
            });
            const data = await res.json();
            if (data.workflows && Array.isArray(data.workflows)) {
                setWorkflows(data.workflows);
            }
        } catch (e) {
            console.error(e);
        } finally {
            setWorkflowsLoading(false);
        }
    };

    const filtered = useMemo(() => {
        const normalized = searchTerm.trim().toLowerCase();
        const dataset = abilities || [];
        if (!normalized) return dataset;
        return dataset.filter((ability) => {
            return [ability.label, ability.description, ability.category, ability.id]
                .map((value) => (value || "").toLowerCase())
                .some((text) => text.includes(normalized));
        });
    }, [abilities, searchTerm]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
    const currentPage = Math.min(page, totalPages);
    const paginated = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize);

    const toggleAbility = (id) => {
        setBuilderAbilities((prev) =>
            prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
        );
    };

    const handleSave = async () => {
        if (!builderName.trim()) {
            alert("Name your workflow before saving.");
            return;
        }
        if (builderAbilities.length === 0) {
            alert("Add at least one ability to the workflow.");
            return;
        }

        try {
            setSavingWorkflow(true);
            const endpoint = editingId ? `${workflowsRestUrl}/${editingId}` : workflowsRestUrl;
            const method = editingId ? "PUT" : "POST";
            const res = await fetch(endpoint, {
                method,
                headers: {
                    "Content-Type": "application/json",
                    "X-WP-Nonce": wpNonce,
                },
                body: JSON.stringify({
                    id: editingId,
                    name: builderName,
                    abilities: builderAbilities,
                    prompt: builderPrompt || buildWorkflowPrompt(builderAbilities, abilities),
                }),
            });

            if (!res.ok) {
                const err = await res.json().catch(() => ({}));
                throw new Error(err.message || "Unable to save workflow");
            }

            await loadWorkflows();
            resetBuilder();
        } catch (e) {
            console.error(e);
            alert(e.message || "Unable to save workflow.");
        } finally {
            setSavingWorkflow(false);
        }
    };

    const resetBuilder = () => {
        setBuilderName("");
        setBuilderPrompt("");
        setBuilderAbilities([]);
        setEditingId("");
    };

    const handleEdit = (workflow) => {
        setEditingId(workflow.id);
        setBuilderName(workflow.name || "");
        setBuilderAbilities(workflow.abilities || []);
        setBuilderPrompt(workflow.prompt || "");
    };

    const handleDelete = async (workflow) => {
        if (!confirm(`Delete workflow "${workflow.name}"?`)) return;
        try {
            const res = await fetch(`${workflowsRestUrl}/${workflow.id}`, {
                method: "DELETE",
                headers: {
                    "X-WP-Nonce": wpNonce,
                },
            });
            if (!res.ok) {
                throw new Error("Failed to delete workflow");
            }
            await loadWorkflows();
            if (editingId === workflow.id) {
                resetBuilder();
            }
        } catch (e) {
            console.error(e);
            alert(e.message || "Failed to delete workflow.");
        }
    };

    const handleDrop = (event) => {
        event.preventDefault();
        const id = event.dataTransfer.getData("text/plain");
        if (id) {
            toggleAbility(id);
        }
    };

    const handleDragStart = (event, abilityId) => {
        event.dataTransfer.setData("text/plain", abilityId);
    };

    return (
        <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-4 aah-space-y-4">
            <div className="aah-flex aah-flex-col md:aah-flex-row aah-items-start md:aah-items-center aah-justify-between aah-gap-4">
                <div>
                    <h2 className="aah-text-base aah-font-medium">Workflow Builder</h2>
                    <p className="aah-text-xs aah-text-slate-500">
                        Search abilities, drag them into a workflow, preview the prompt, and save.
                    </p>
                </div>
                <div className="aah-flex aah-gap-2 aah-items-center">
                    <label className="aah-text-[11px] aah-text-slate-600">Per page</label>
                    <select
                        value={pageSize}
                        onChange={(e) => setPageSize(parseInt(e.target.value, 10))}
                        className="aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-px-2 aah-py-1 aah-text-xs"
                    >
                        {[5, 10, 15, 20].map((size) => (
                            <option key={size} value={size}>
                                {size}
                            </option>
                        ))}
                    </select>
                </div>
            </div>

            <div className="aah-grid aah-grid-cols-1 lg:aah-grid-cols-2 aah-gap-4">
                <div className="aah-space-y-2">
                    <div className="aah-flex aah-items-center aah-justify-between">
                        <input
                            type="search"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            placeholder="Search abilities…"
                            className="aah-w-full aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-px-3 aah-py-2 aah-text-sm"
                        />
                    </div>

                    {loading ? (
                        <p className="aah-text-xs aah-text-slate-500">Loading abilities…</p>
                    ) : (
                        <div className="aah-space-y-2">
                            {paginated.map((ability) => (
                                <div
                                    key={ability.id}
                                    draggable
                                    onDragStart={(e) => handleDragStart(e, ability.id)}
                                    className="aah-rounded-xl aah-border aah-border-slate-100 aah-bg-slate-50 aah-p-3 aah-flex aah-flex-col aah-gap-1 aah-cursor-move"
                                >
                                    <div className="aah-flex aah-items-start aah-justify-between aah-gap-2">
                                        <div>
                                            <p className="aah-text-[11px] aah-text-slate-500">{ability.id}</p>
                                            <h3 className="aah-text-sm aah-font-semibold aah-text-slate-900">{ability.label}</h3>
                                        </div>
                                        <button
                                            type="button"
                                            className={`aah-text-[10px] aah-rounded-full aah-px-2 aah-py-0.5 ${
                                                builderAbilities.includes(ability.id)
                                                    ? "aah-bg-emerald-100 aah-text-emerald-700"
                                                    : "aah-bg-slate-200 aah-text-slate-700"
                                            }`}
                                            onClick={() => toggleAbility(ability.id)}
                                        >
                                            {builderAbilities.includes(ability.id) ? "Added" : "Add"}
                                        </button>
                                    </div>
                                    <p className="aah-text-xs aah-text-slate-600">{ability.description}</p>
                                </div>
                            ))}
                        </div>
                    )}

                    <div className="aah-flex aah-justify-between aah-items-center aah-text-[11px] aah-text-slate-600">
                        <button
                            type="button"
                            className="aah-rounded-full aah-border aah-border-slate-200 aah-bg-white aah-px-3 aah-py-1"
                            onClick={() => setPage(Math.max(1, currentPage - 1))}
                            disabled={currentPage === 1}
                        >
                            Previous
                        </button>
                        <span>
                            Page {currentPage} of {totalPages}
                        </span>
                        <button
                            type="button"
                            className="aah-rounded-full aah-border aah-border-slate-200 aah-bg-white aah-px-3 aah-py-1"
                            onClick={() => setPage(Math.min(totalPages, currentPage + 1))}
                            disabled={currentPage === totalPages}
                        >
                            Next
                        </button>
                    </div>
                </div>

                <div
                    className="aah-rounded-xl aah-border aah-border-emerald-200 aah-bg-emerald-50 aah-p-3 aah-space-y-2"
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={handleDrop}
                >
                    <div className="aah-flex aah-items-center aah-justify-between">
                        <div>
                            <div className="aah-font-semibold">Workflow canvas</div>
                            <p className="aah-text-[11px] aah-text-emerald-700">
                                Drag abilities here or click “Add” to include them in the workflow.
                            </p>
                        </div>
                        <button
                            type="button"
                            className="aah-text-[11px] aah-text-emerald-800 aah-underline"
                            onClick={resetBuilder}
                        >
                            Clear
                        </button>
                    </div>

                    <input
                        type="text"
                        placeholder="Workflow name"
                        value={builderName}
                        onChange={(e) => setBuilderName(e.target.value)}
                        className="aah-w-full aah-rounded-md aah-border aah-border-emerald-200 aah-bg-white aah-px-2 aah-py-1"
                    />

                    <div className="aah-flex aah-flex-wrap aah-gap-1">
                        {builderAbilities.length === 0 && (
                            <span className="aah-text-[11px] aah-text-emerald-700">No abilities yet.</span>
                        )}
                        {builderAbilities.map((id) => {
                            const ability = abilities.find((item) => item.id === id);
                            return (
                                <span
                                    key={id}
                                    className="aah-inline-flex aah-items-center aah-gap-1 aah-rounded-full aah-bg-white aah-border aah-border-emerald-200 aah-px-2 aah-py-1"
                                >
                                    {ability?.label || id}
                                    <button
                                        type="button"
                                        className="aah-text-[10px] aah-text-emerald-700"
                                        onClick={() => toggleAbility(id)}
                                    >
                                        ✕
                                    </button>
                                </span>
                            );
                        })}
                    </div>

                    <textarea
                        value={builderPrompt}
                        onChange={(e) => setBuilderPrompt(e.target.value)}
                        rows={4}
                        className="aah-w-full aah-rounded-md aah-border aah-border-emerald-200 aah-bg-white aah-px-2 aah-py-1 aah-text-[12px]"
                        placeholder="Prompt preview built from abilities"
                    />

                    <div className="aah-flex aah-gap-2">
                        <button
                            type="button"
                            className="aah-inline-flex aah-items-center aah-justify-center aah-rounded-md aah-bg-emerald-600 aah-text-white aah-px-3 aah-py-1.5 aah-text-[12px] aah-font-medium disabled:aah-opacity-60"
                            onClick={handleSave}
                            disabled={savingWorkflow}
                        >
                            {savingWorkflow ? "Saving…" : editingId ? "Update workflow" : "Save workflow"}
                        </button>
                        {editingId && (
                            <button
                                type="button"
                                className="aah-inline-flex aah-items-center aah-justify-center aah-rounded-md aah-border aah-border-emerald-600 aah-text-emerald-700 aah-px-3 aah-py-1.5 aah-text-[12px]"
                                onClick={resetBuilder}
                            >
                                Cancel edit
                            </button>
                        )}
                    </div>
                </div>
            </div>

            <div className="aah-space-y-2">
                <div className="aah-flex aah-items-center aah-justify-between">
                    <h3 className="aah-text-sm aah-font-semibold">Saved workflows</h3>
                    {workflowsLoading && <span className="aah-text-[11px] aah-text-slate-500">Loading…</span>}
                </div>

                {workflows.length === 0 && !workflowsLoading && (
                    <p className="aah-text-xs aah-text-slate-500">No workflows saved yet. Build one on the right.</p>
                )}

                <div className="aah-grid aah-grid-cols-1 md:aah-grid-cols-2 aah-gap-3">
                    {workflows.map((workflow) => (
                        <div
                            key={workflow.id}
                            className="aah-rounded-xl aah-border aah-border-slate-100 aah-bg-slate-50 aah-p-3 aah-space-y-1"
                        >
                            <div className="aah-flex aah-items-start aah-justify-between">
                                <div>
                                    <div className="aah-font-semibold">{workflow.name}</div>
                                    <div className="aah-text-[11px] aah-text-slate-500">{workflow.abilities?.length || 0} abilities</div>
                                </div>
                                <div className="aah-flex aah-gap-1">
                                    <button
                                        type="button"
                                        className="aah-text-[11px] aah-rounded-full aah-bg-white aah-border aah-border-slate-200 aah-px-2 aah-py-1"
                                        onClick={() => handleEdit(workflow)}
                                    >
                                        Edit
                                    </button>
                                    <button
                                        type="button"
                                        className="aah-text-[11px] aah-rounded-full aah-bg-rose-50 aah-border aah-border-rose-200 aah-text-rose-700 aah-px-2 aah-py-1"
                                        onClick={() => handleDelete(workflow)}
                                    >
                                        Delete
                                    </button>
                                </div>
                            </div>
                            {workflow.prompt && (
                                <p className="aah-text-[11px] aah-text-slate-600 aah-line-clamp-2">{workflow.prompt}</p>
                            )}
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}

function buildWorkflowPrompt(selectedAbilities, abilities) {
    if (!selectedAbilities || selectedAbilities.length === 0) {
        return "Select abilities to build a workflow prompt.";
    }

    const details = selectedAbilities
        .map((id, index) => {
            const ability = abilities.find((item) => item.id === id);
            if (!ability) return `${index + 1}. ${id}`;
            return `${index + 1}. ${ability.label} — ${ability.description}`;
        })
        .join("\n");

    return `Combine these abilities in order and summarize outputs clearly:\n${details}`;
}

function DocumentationView() {
    return (
        <div className="aah-space-y-5">
            {/* Getting Started */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <h2 className="aah-text-xl aah-font-semibold aah-mb-4 aah-text-slate-900">
                    Getting Started
                </h2>
                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <p>
                        <strong>AI Workflow Automation – AI Agent Hub</strong> is a modern WordPress AI plugin built for WordPress 6.9+
                        and the new <strong>Abilities API</strong>. It turns your dashboard into a central AI control hub where you can
                        connect multiple AI providers and run AI-powered content analysis.
                    </p>

                    <div className="aah-bg-blue-50 aah-border aah-border-blue-200 aah-rounded-lg aah-p-4">
                        <h3 className="aah-font-semibold aah-text-blue-900 aah-mb-2">Requirements</h3>
                        <ul className="aah-list-disc aah-list-inside aah-space-y-1 aah-text-blue-800">
                            <li>WordPress <strong>6.9</strong> or higher</li>
                            <li>PHP <strong>7.4</strong> or higher</li>
                            <li>At least one AI provider configured via <strong>Settings → AI Credentials</strong></li>
                        </ul>
                    </div>
                </div>
            </section>

            {/* AI Content Steward */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <div className="aah-flex aah-items-center aah-gap-2 aah-mb-4">
                    <h2 className="aah-text-xl aah-font-semibold aah-text-slate-900">
                        AI Content Steward
                    </h2>
                    <span className="aah-text-xs aah-uppercase aah-tracking-wide aah-bg-emerald-100 aah-text-emerald-700 aah-px-2 aah-py-1 aah-rounded-full">
                        Active
                    </span>
                </div>

                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <p>
                        The <strong>AI Content Steward</strong> module is your AI content assistant inside the post/page editor.
                    </p>

                    <div className="aah-space-y-3">
                        <div>
                            <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">How to Use:</h3>
                            <ol className="aah-list-decimal aah-list-inside aah-space-y-2 aah-pl-2">
                                <li>Open any <strong>post</strong> or <strong>page</strong> in the WordPress editor</li>
                                <li>Look for the <strong>"AI Content Steward"</strong> meta box in the sidebar</li>
                                <li>Choose your preferred AI provider:
                                    <ul className="aah-list-disc aah-list-inside aah-pl-6 aah-mt-1 aah-space-y-1">
                                        <li><strong>Auto</strong> – automatically picks any configured provider</li>
                                        <li><strong>OpenAI</strong> (ChatGPT)</li>
                                        <li><strong>Google Gemini</strong></li>
                                        <li><strong>Anthropic Claude</strong></li>
                                    </ul>
                                </li>
                            </ol>
                        </div>

                        <div className="aah-bg-slate-50 aah-rounded-lg aah-p-4 aah-space-y-3">
                            <div>
                                <h4 className="aah-font-semibold aah-text-slate-900 aah-mb-1">Analyze Post</h4>
                                <p>Click the <strong>"Analyze Post"</strong> button to send your content to AI for analysis. You'll receive:</p>
                                <ul className="aah-list-disc aah-list-inside aah-pl-4 aah-mt-1 aah-space-y-1">
                                    <li><strong>Summary</strong> – concise overview (max 3 sentences)</li>
                                    <li><strong>Reading level</strong> – Beginner / Intermediate / Advanced</li>
                                    <li><strong>Suggestions</strong> – improvement tips for your content</li>
                                </ul>
                            </div>

                            <div>
                                <h4 className="aah-font-semibold aah-text-slate-900 aah-mb-1">Suggest Titles</h4>
                                <p>Click <strong>"Suggest Titles"</strong> to generate SEO-optimized title ideas. Perfect for:</p>
                                <ul className="aah-list-disc aah-list-inside aah-pl-4 aah-mt-1 aah-space-y-1">
                                    <li>Improving click-through rate (CTR) from search results</li>
                                    <li>Testing different angles for blog posts</li>
                                    <li>Quickly brainstorming alternative headlines</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            {/* AI Providers Setup */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <h2 className="aah-text-xl aah-font-semibold aah-mb-4 aah-text-slate-900">
                    Setting Up AI Providers
                </h2>

                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <p>
                        To use the AI features, you need to configure at least one AI provider with valid API credentials.
                    </p>

                    <div className="aah-bg-amber-50 aah-border aah-border-amber-200 aah-rounded-lg aah-p-4">
                        <h3 className="aah-font-semibold aah-text-amber-900 aah-mb-2">Configuration Steps:</h3>
                        <ol className="aah-list-decimal aah-list-inside aah-space-y-2 aah-text-amber-900">
                            <li>Go to <strong>Settings → AI Credentials</strong> in WordPress admin</li>
                            <li>Add your API key(s) for your preferred provider(s)</li>
                            <li>Return to the <strong>AI Agent Hub Dashboard</strong> to verify provider status</li>
                            <li>Look for <strong>✅ Ready</strong> status next to your configured providers</li>
                        </ol>
                    </div>

                    <div>
                        <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">Supported Providers:</h3>
                        <div className="aah-grid aah-grid-cols-1 md:aah-grid-cols-3 aah-gap-3">
                            <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-3">
                                <div className="aah-font-semibold">OpenAI</div>
                                <div className="aah-text-xs aah-text-slate-600">GPT-4, GPT-3.5 models</div>
                            </div>
                            <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-3">
                                <div className="aah-font-semibold">Google Gemini</div>
                                <div className="aah-text-xs aah-text-slate-600">Gemini Pro and other models</div>
                            </div>
                            <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-3">
                                <div className="aah-font-semibold">Anthropic Claude</div>
                                <div className="aah-text-xs aah-text-slate-600">Claude 3 family models</div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            {/* Workflows */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <h2 className="aah-text-xl aah-font-semibold aah-mb-4 aah-text-slate-900">
                    Working with Workflows
                </h2>

                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <p>
                        The Workflows tab allows you to create custom AI automation workflows by combining multiple abilities.
                    </p>

                    <div className="aah-space-y-3">
                        <div>
                            <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">Creating a Workflow:</h3>
                            <ol className="aah-list-decimal aah-list-inside aah-space-y-2 aah-pl-2">
                                <li>Navigate to the <strong>Workflows</strong> tab in AI Agent Hub</li>
                                <li>Search for abilities you want to include in your workflow</li>
                                <li>Drag abilities to the workflow canvas or click <strong>"Add"</strong></li>
                                <li>Give your workflow a descriptive name</li>
                                <li>Review the auto-generated prompt (you can customize it)</li>
                                <li>Click <strong>"Save workflow"</strong></li>
                            </ol>
                        </div>

                        <div className="aah-bg-slate-50 aah-rounded-lg aah-p-4">
                            <h4 className="aah-font-semibold aah-text-slate-900 aah-mb-2">Managing Workflows:</h4>
                            <ul className="aah-list-disc aah-list-inside aah-space-y-1">
                                <li><strong>Edit</strong> – modify existing workflows by clicking the Edit button</li>
                                <li><strong>Delete</strong> – remove workflows you no longer need</li>
                                <li><strong>Search</strong> – quickly find specific abilities using the search box</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </section>

            {/* Upcoming Features */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <div className="aah-flex aah-items-center aah-gap-2 aah-mb-4">
                    <h2 className="aah-text-xl aah-font-semibold aah-text-slate-900">
                        Upcoming Features
                    </h2>
                    <span className="aah-text-xs aah-uppercase aah-tracking-wide aah-bg-amber-100 aah-text-amber-700 aah-px-2 aah-py-1 aah-rounded-full">
                        Coming Soon
                    </span>
                </div>

                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <div className="aah-grid aah-grid-cols-1 md:aah-grid-cols-2 aah-gap-4">
                        <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-4">
                            <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">AI Store Manager (WooCommerce)</h3>
                            <p className="aah-text-xs aah-text-slate-600">
                                AI-powered WooCommerce assistant for product descriptions, store insights,
                                and identifying content gaps.
                            </p>
                        </div>

                        <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-4">
                            <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">AI Support Desk</h3>
                            <p className="aah-text-xs aah-text-slate-600">
                                Lightweight AI support assistant to summarize comment threads and suggest reply drafts.
                            </p>
                        </div>

                        <div className="aah-border aah-border-slate-200 aah-rounded-lg aah-p-4 aah-col-span-1 md:aah-col-span-2">
                            <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">AI Automation Recipes / Workflows</h3>
                            <p className="aah-text-xs aah-text-slate-600">
                                Create simple AI automations on WordPress events (e.g., "When a post is published → run content analysis → save summary").
                            </p>
                        </div>
                    </div>
                </div>
            </section>

            {/* Troubleshooting */}
            <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-6">
                <h2 className="aah-text-xl aah-font-semibold aah-mb-4 aah-text-slate-900">
                    Troubleshooting
                </h2>

                <div className="aah-space-y-4 aah-text-sm aah-text-slate-700">
                    <div>
                        <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">
                            "AI analysis failed. Check AI credentials or logs"
                        </h3>
                        <p className="aah-mb-2">This usually means:</p>
                        <ul className="aah-list-disc aah-list-inside aah-space-y-1 aah-pl-4">
                            <li>No AI provider is configured for text generation</li>
                            <li>Your API key is invalid or missing required permissions</li>
                            <li>The selected model does not support text generation</li>
                            <li>Network or API error occurred</li>
                        </ul>

                        <div className="aah-bg-blue-50 aah-border aah-border-blue-200 aah-rounded-lg aah-p-3 aah-mt-3">
                            <h4 className="aah-font-semibold aah-text-blue-900 aah-mb-1">How to fix:</h4>
                            <ol className="aah-list-decimal aah-list-inside aah-space-y-1 aah-text-blue-800">
                                <li>Go to <strong>Settings → AI Credentials</strong> and verify at least one provider is configured</li>
                                <li>Enable <code className="aah-bg-blue-100 aah-px-1 aah-rounded">WP_DEBUG_LOG</code> and check <code className="aah-bg-blue-100 aah-px-1 aah-rounded">debug.log</code> for errors</li>
                                <li>Ensure you're running WordPress 6.9+ with all dependencies installed</li>
                            </ol>
                        </div>
                    </div>

                    <div>
                        <h3 className="aah-font-semibold aah-text-slate-900 aah-mb-2">
                            Provider shows "Not configured / unsupported"
                        </h3>
                        <p>
                            This means the provider hasn't been set up yet in <strong>Settings → AI Credentials</strong>.
                            Add your API key for that specific provider to enable it.
                        </p>
                    </div>
                </div>
            </section>

            {/* Support */}
            <section className="aah-bg-gradient-to-br aah-from-slate-900 aah-to-slate-700 aah-rounded-2xl aah-shadow-sm aah-p-6 aah-text-white">
                <h2 className="aah-text-xl aah-font-semibold aah-mb-3">
                    Need Help?
                </h2>
                <p className="aah-text-sm aah-text-slate-200 aah-mb-4">
                    Have questions or need assistance? Our support team is here to help you get the most out of AI Agent Hub.
                </p>
                <a
                    href={AwfahConfig.supportUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="aah-inline-flex aah-items-center aah-justify-center aah-rounded-lg aah-bg-white aah-text-slate-900 aah-px-4 aah-py-2 aah-text-sm aah-font-medium hover:aah-bg-slate-100"
                >
                    Contact Support →
                </a>
            </section>
        </div>
    );
}

function AdminApp() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [modules, setModules] = useState(AwfahConfig.modules || {});
    const [providers, setProviders] = useState([]);
    const [providersLoading, setProvidersLoading] = useState(true);
    const [abilitiesLoading, setAbilitiesLoading] = useState(true);
    const [abilities, setAbilities] = useState([]);
    const [activeTab, setActiveTab] = useState("dashboard");

    const fetchSettings = async () => {
        try {
            setLoading(true);
            const res = await fetch(`${AwfahConfig.restUrl}/settings`, {
                headers: {
                    "X-WP-Nonce": AwfahConfig.wpNonce,
                },
            });
            const data = await res.json();
            if (data.settings && data.settings.modules) {
                setModules(data.settings.modules);
            }
        } catch (e) {
            console.error(e);
            toast.error("Failed to load AI Agent Hub settings.");
        } finally {
            setLoading(false);
        }
    };

    const fetchProviders = async () => {
        try {
            setProvidersLoading(true);
            const res = await fetch(AwfahConfig.providersRestUrl, {
                headers: {
                    "X-WP-Nonce": AwfahConfig.wpNonce,
                },
            });
            if (!res.ok) {
                throw new Error("Failed to load providers");
            }
            const data = await res.json();
            if (data.providers && Array.isArray(data.providers)) {
                setProviders(data.providers);
            }
        } catch (e) {
            console.error(e);
        } finally {
            setProvidersLoading(false);
        }
    };

    const fetchAbilities = async () => {
        if (!AwfahConfig.abilitiesRestUrl) {
            setAbilitiesLoading(false);
            return;
        }

        try {
            setAbilitiesLoading(true);
            const res = await fetch(AwfahConfig.abilitiesRestUrl, {
                headers: {
                    "X-WP-Nonce": AwfahConfig.wpNonce,
                },
            });

            if (!res.ok) {
                throw new Error("Failed to load abilities");
            }

            const data = await res.json();
            if (data.abilities && Array.isArray(data.abilities)) {
                setAbilities(data.abilities);
            }
        } catch (e) {
            console.error(e);
            toast.error("Unable to load abilities.");
        } finally {
            setAbilitiesLoading(false);
        }
    };

    const saveSettings = async (nextModules) => {
        try {
            setSaving(true);
            const res = await fetch(`${AwfahConfig.restUrl}/settings`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-WP-Nonce": AwfahConfig.wpNonce,
                },
                body: JSON.stringify({ modules: nextModules }),
            });
            const data = await res.json();
            if (data.settings && data.settings.modules) {
                setModules(data.settings.modules);
            }
            toast.success("Settings saved.");
        } catch (e) {
            console.error(e);
            toast.error("Failed to save settings.");
        } finally {
            setSaving(false);
        }
    };

    useEffect(() => {
        fetchSettings();
        fetchProviders();
        fetchAbilities();
    }, []);

    const handleToggle = (key, value) => {
        const next = { ...modules, [key]: value };
        setModules(next);
        saveSettings(next);
    };

    return (
        <div className="aah-min-h-screen aah-bg-slate-50 aah-text-slate-900 aah-p-6">
            <div className="aah-max-w-5xl aah-mx-auto">
                {/* Header */}
                <header className="aah-mb-6">
                    <div className="aah-flex aah-items-center aah-justify-between aah-gap-4">
                        <div>
                            <h1 className="aah-text-2xl aah-font-semibold aah-flex aah-items-center aah-gap-2">
                <span className="aah-inline-flex aah-h-8 aah-w-8 aah-items-center aah-justify-center aah-rounded-xl aah-bg-slate-900 aah-text-white aah-text-lg">
                  🤖
                </span>
                                AtlasAgent By AtlasAiDev
                            </h1>
                            <p className="aah-text-sm aah-text-slate-600 aah-mt-1">
                                Central hub for multi-provider AI agents and automations.
                            </p>
                        </div>

                        <a
                            href={AwfahConfig.supportUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="aah-inline-flex aah-items-center aah-justify-center aah-rounded-full aah-border aah-border-slate-300 aah-bg-white aah-px-3 aah-py-1.5 aah-text-xs aah-font-medium aah-text-slate-800 hover:aah-bg-slate-100"
                        >
                            Need help? <span className="aah-ml-1">Contact Support →</span>
                        </a>
                    </div>

                    <div className="aah-flex aah-gap-2 aah-mt-4">
                        {NAV_ITEMS.map((item) => (
                            <button
                                key={item.id}
                                className={`aah-text-xs aah-font-medium aah-rounded-full aah-px-3 aah-py-1.5 aah-border ${
                                    activeTab === item.id
                                        ? "aah-bg-slate-900 aah-text-white aah-border-slate-900"
                                        : "aah-bg-white aah-text-slate-800 aah-border-slate-200 hover:aah-bg-slate-100"
                                }`}
                                onClick={() => setActiveTab(item.id)}
                                type="button"
                            >
                                {item.label}
                            </button>
                        ))}
                    </div>

                    {(loading || saving) && (
                        <p className="aah-text-xs aah-text-slate-500 aah-mt-2">
                            {loading ? "Loading settings…" : "Saving settings…"}
                        </p>
                    )}
                </header>

                {activeTab === "dashboard" && (
                    <>
                        {/* Providers / AI Agents */}
                        <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-4 aah-mb-5">
                            <div className="aah-flex aah-items-center aah-justify-between aah-gap-4 aah-mb-3">
                                <div>
                                    <h2 className="aah-text-base aah-font-medium">
                                        Connected AI Agents
                                    </h2>
                                    <p className="aah-text-xs aah-text-slate-500">
                                        These providers are configured via <strong>Settings → AI Credentials</strong>.
                                    </p>
                                </div>
                            </div>

                            {providersLoading ? (
                                <p className="aah-text-xs aah-text-slate-500">
                                    Checking configured providers…
                                </p>
                            ) : providers.length === 0 ? (
                                <p className="aah-text-xs aah-text-slate-500">
                                    No AI providers detected. Configure them under{" "}
                                    <strong>Settings → AI Credentials</strong>.
                                </p>
                            ) : (
                                <div className="aah-grid aah-grid-cols-1 sm:aah-grid-cols-2 md:aah-grid-cols-3 aah-gap-3">
                                    {providers.map((p) => (
                                        <div
                                            key={p.id}
                                            className="aah-rounded-xl aah-border aah-border-slate-100 aah-bg-slate-50 aah-p-3 aah-flex aah-flex-col aah-gap-1"
                                        >
                                            <div className="aah-text-sm aah-font-medium">{p.label}</div>
                                            <div className="aah-text-[11px] aah-text-slate-600">
                                                {p.id === "auto"
                                                    ? "Automatically uses any configured provider."
                                                    : "Direct preference when selected in tools."}
                                            </div>
                                            <div className="aah-text-[11px] aah-font-semibold">
                                                Status:{" "}
                                                {p.supported
                                                    ? "✅ Ready"
                                                    : "⚠️ Not configured / unsupported"}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </section>

                        {/* Modules */}
                        <section className="aah-bg-white aah-rounded-2xl aah-shadow-sm aah-border aah-border-slate-100 aah-p-4">
                            <div className="aah-flex aah-justify-between aah-items-center aah-gap-4 aah-mb-3">
                                <div>
                                    <h2 className="aah-text-base aah-font-medium">
                                        Modules & Features
                                    </h2>
                                    <p className="aah-text-xs aah-text-slate-500">
                                        Enable AI modules. Some modules are marked as{" "}
                                        <strong>Coming soon</strong> and don&apos;t expose full UI yet.
                                    </p>
                                </div>
                            </div>

                            <div className="aah-space-y-3">
                                {Object.entries(MODULE_LABELS).map(([key, info]) => {
                                    const isComingSoon = key === "support_desk" || key === "automations";
                                    const isActive = !isComingSoon && !!modules[key];

                                    return (
                                        <div
                                            key={key}
                                            className="aah-flex aah-items-center aah-justify-between aah-gap-4 aah-rounded-xl aah-border aah-border-slate-100 aah-bg-slate-50 aah-p-3"
                                        >
                                            <div>
                                                <div className="aah-flex aah-items-center aah-gap-2">
                                                    <h3 className="aah-text-sm aah-font-medium">
                                                        {info.title}
                                                    </h3>
                                                    {isComingSoon && (
                                                        <span className="aah-text-[10px] aah-uppercase aah-tracking-wide aah-bg-amber-100 aah-text-amber-700 aah-px-2 aah-py-0.5 aah-rounded-full">
                          Coming soon
                        </span>
                                                    )}
                                                    {!isComingSoon && isActive && (
                                                        <span className="aah-text-[10px] aah-uppercase aah-tracking-wide aah-bg-emerald-100 aah-text-emerald-700 aah-px-2 aah-py-0.5 aah-rounded-full">
                          Active
                        </span>
                                                    )}
                                                </div>
                                                <p className="aah-text-xs aah-text-slate-600 aah-mt-0.5">
                                                    {info.description}
                                                </p>
                                                <p className="aah-text-[11px] aah-text-slate-500 aah-mt-0.5">
                                                    Status: {info.status}
                                                </p>
                                            </div>
                                            <Toggle
                                                checked={!!modules[key]}
                                                onChange={(value) => handleToggle(key, value)}
                                                disabled={isComingSoon}
                                            />
                                        </div>
                                    );
                                })}
                            </div>
                        </section>
                    </>
                )}

                {activeTab === "workflows" && (
                    <WorkflowsView
                        abilities={abilities}
                        loading={abilitiesLoading}
                        wpNonce={AwfahConfig.wpNonce}
                        workflowsRestUrl={AwfahConfig.workflowsRestUrl}
                    />
                )}

                {activeTab === "documentation" && <DocumentationView />}
            </div>

            <ToastContainer position="bottom-right" />
        </div>
    );
}

document.addEventListener("DOMContentLoaded", () => {
    const rootEl = document.getElementById("ai-workflow-automation-ai-agent-hub-root");
    if (!rootEl) return;
    const root = createRoot(rootEl);
    root.render(<AdminApp />);
});

