import React, { useEffect, useMemo, useState } from 'react';

type DashboardBootstrap = {
    companyName: string;
    fullName: string;
    plan: string;
    tenantStatus: string;
    branchesCount: number;
    usersCount: number;
    aiEnabled: boolean;
    aiFeatures: string[];
    aiInteractionsCount: number;
    aiKnowledgeCount: number;
    dashboardEndpoint: string;
    onboardingCompleted: boolean;
    aiEndpoint: string | null;
    aiDemoConversationLabel: string | null;
    copilotEndpoint: string;
    inboxUrl: string;
    ordersUrl: string;
    pipelineUrl: string;
    messagesEndpointBase: string;
    leadsEndpointBase: string;
    quotesEndpoint: string;
    createOrderEndpoint: string;
    canReplyConversations: boolean;
    canMoveLeads: boolean;
    canManageQuotes: boolean;
    canManageOrders: boolean;
    csrfToken: string | null;
};

type DashboardMetrics = {
    unreadConversations: number;
    unassignedConversations: number;
    openLeads: number;
    wonLeads: number;
    ordersCount: number;
    quotesPending: number;
    overdueTasks: number;
    aiInteractions: number;
    revenueTotal: number;
};

type SalesCopilotResponse = {
    available: boolean;
    reason?: string;
    focusConversation?: {
        id: string;
        customerName: string;
        channel: string;
        city: string | null;
        priority: string;
        status: string;
        unreadCount: number;
        assignee: string;
        latestCustomerMessage: string | null;
        recentTimeline: Array<{
            direction: string;
            text: string;
            time: string | null;
        }>;
    };
    lead?: {
        id: string;
        title: string;
        status: string;
        stage: string | null;
        value: string | null;
        nextStage: {
            id: string;
            name: string;
        } | null;
    } | null;
    quote?: {
        id: string;
        quoteNumber: string;
        status: string;
        total: string;
    } | null;
    order?: {
        id: string;
        orderNumber: string;
        status: string;
        paymentStatus: string;
        total: string;
    } | null;
    replySuggestion?: {
        reply_text: string;
        detected_intent: string;
        confidence: number | null;
        warnings: string[];
        provider: string;
        model: string | null;
        prompt_version: string;
        human_approval_required: boolean;
        validation_state: string;
    };
    orderDraft?: {
        conversation_id?: string;
        contact_id?: string;
        order_signal_detected: boolean;
        ready_to_create: boolean;
        shipping_city: string | null;
        notes: string;
        missing_fields: string[];
        warnings: string[];
        items: Array<{
            product_id: string;
            product_name: string;
            quantity: number;
            unit_price_formatted: string;
            stock_quantity: number;
        }>;
    };
    copilot?: {
        headline: string;
        nextBestAction: string;
        followUpRecommendation: string;
        riskFlags: string[];
    };
};

const moduleCards = [
    {
        title: 'Inbox Workspace',
        status: 'Live',
        description: 'Shared inbox, assignment, unread filters, notes, tags, and fast agent workflows.',
    },
    {
        title: 'Lead Pipeline',
        status: 'Ready',
        description: 'Default pipeline and stage movement already support structured selling and review.',
    },
    {
        title: 'AI Sales Copilot',
        status: 'Live',
        description: 'Conversation review, reply guidance, order readiness, and next-best-action recommendations.',
    },
];

function cn(...values: Array<string | false | null | undefined>) {
    return values.filter(Boolean).join(' ');
}

function formatIntent(intent: string) {
    return intent
        .split('_')
        .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
        .join(' ');
}

function StatCard({
    label,
    value,
    accent,
    help,
}: {
    label: string;
    value: string;
    accent: string;
    help: string;
}) {
    return (
        <div className="rounded-[28px] border border-slate-200/80 bg-white/90 p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)] backdrop-blur">
            <div className="flex items-start justify-between gap-4">
                <div>
                    <p className="text-sm font-medium text-slate-500">{label}</p>
                    <p className="mt-3 text-3xl font-semibold tracking-tight text-slate-950">{value}</p>
                    <p className="mt-2 text-sm text-slate-500">{help}</p>
                </div>

                <div className={cn('h-11 w-11 rounded-2xl', accent)} />
            </div>
        </div>
    );
}

function Badge({
    children,
    tone = 'slate',
}: {
    children: React.ReactNode;
    tone?: 'slate' | 'emerald' | 'amber' | 'rose' | 'blue' | 'violet';
}) {
    const tones: Record<string, string> = {
        slate: 'bg-slate-100 text-slate-700',
        emerald: 'bg-emerald-100 text-emerald-700',
        amber: 'bg-amber-100 text-amber-700',
        rose: 'bg-rose-100 text-rose-700',
        blue: 'bg-blue-100 text-blue-700',
        violet: 'bg-violet-100 text-violet-700',
    };

    return (
        <span className={cn('inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold', tones[tone])}>
            {children}
        </span>
    );
}

export function DashboardWorkspace({ bootstrap }: { bootstrap: DashboardBootstrap }) {
    const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
    const [copilot, setCopilot] = useState<SalesCopilotResponse | null>(null);
    const [copilotLoading, setCopilotLoading] = useState(false);
    const [actionLoading, setActionLoading] = useState<string | null>(null);
    const [copilotError, setCopilotError] = useState<string | null>(null);

    const readinessLabel = useMemo(() => {
        if (!bootstrap.aiEnabled) {
            return 'AI disabled';
        }

        if (bootstrap.aiFeatures.length >= 5) {
            return 'AI ready';
        }

        return 'AI foundation';
    }, [bootstrap.aiEnabled, bootstrap.aiFeatures.length]);

    useEffect(() => {
        async function loadMetrics() {
            const response = await fetch(bootstrap.dashboardEndpoint, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });

            const json = await response.json();
            setMetrics(json.data);
        }

        void loadMetrics();
    }, [bootstrap.dashboardEndpoint]);

    async function runCopilot() {
        setCopilotLoading(true);
        setCopilotError(null);

        try {
            const response = await fetch(bootstrap.copilotEndpoint, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not run AI Sales Copilot.');
            }

            setCopilot(json.data as SalesCopilotResponse);
        } catch (error) {
            setCopilotError(error instanceof Error ? error.message : 'Could not run AI Sales Copilot.');
        } finally {
            setCopilotLoading(false);
        }
    }

    async function sendSuggestedReply() {
        const conversationId = copilot?.focusConversation?.id;
        const replyText = copilot?.replySuggestion?.reply_text;
        if (!conversationId || !replyText) return;

        setActionLoading('reply');
        setCopilotError(null);

        try {
            const response = await fetch(`${bootstrap.messagesEndpointBase}/${conversationId}/messages`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    ...(bootstrap.csrfToken ? { 'X-CSRF-TOKEN': bootstrap.csrfToken } : {}),
                },
                body: JSON.stringify({ body_text: replyText }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not send suggested reply.');
            }
            await runCopilot();
        } catch (error) {
            setCopilotError(error instanceof Error ? error.message : 'Could not send suggested reply.');
        } finally {
            setActionLoading(null);
        }
    }

    async function createQuote() {
        const draft = copilot?.orderDraft;
        if (!draft?.contact_id || !draft.items?.length) return;

        setActionLoading('quote');
        setCopilotError(null);

        try {
            const response = await fetch(bootstrap.quotesEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    ...(bootstrap.csrfToken ? { 'X-CSRF-TOKEN': bootstrap.csrfToken } : {}),
                },
                body: JSON.stringify({
                    contact_id: draft.contact_id,
                    lead_id: copilot?.lead?.id ?? null,
                    status: 'sent',
                    shipping_fee: 0,
                    discount_total: 0,
                    notes: draft.notes,
                    expires_in_days: 7,
                    items: draft.items.map((item) => ({
                        product_id: item.product_id,
                        quantity: item.quantity,
                    })),
                }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not create quote.');
            }
            await runCopilot();
        } catch (error) {
            setCopilotError(error instanceof Error ? error.message : 'Could not create quote.');
        } finally {
            setActionLoading(null);
        }
    }

    async function createOrder() {
        const draft = copilot?.orderDraft;
        if (!draft?.contact_id || !draft.items?.length) return;

        setActionLoading('order');
        setCopilotError(null);

        try {
            const response = await fetch(bootstrap.createOrderEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    ...(bootstrap.csrfToken ? { 'X-CSRF-TOKEN': bootstrap.csrfToken } : {}),
                },
                body: JSON.stringify({
                    contact_id: draft.contact_id,
                    customer_name: copilot?.focusConversation?.customerName ?? null,
                    shipping_city: draft.shipping_city,
                    status: 'new',
                    payment_status: 'unpaid',
                    shipping_fee: 0,
                    discount_total: 0,
                    notes: draft.notes,
                    items: draft.items.map((item) => ({
                        product_id: item.product_id,
                        quantity: item.quantity,
                    })),
                }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not create order.');
            }
            window.location.href = `${bootstrap.ordersUrl}/${json.data.id}`;
        } catch (error) {
            setCopilotError(error instanceof Error ? error.message : 'Could not create order.');
        } finally {
            setActionLoading(null);
        }
    }

    async function moveLeadStage() {
        const lead = copilot?.lead;
        if (!lead?.id || !lead.nextStage?.id) return;

        setActionLoading('lead');
        setCopilotError(null);

        try {
            const response = await fetch(`${bootstrap.leadsEndpointBase}/${lead.id}/move-stage`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    ...(bootstrap.csrfToken ? { 'X-CSRF-TOKEN': bootstrap.csrfToken } : {}),
                },
                body: JSON.stringify({ stage_id: lead.nextStage.id }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not move lead stage.');
            }
            await runCopilot();
        } catch (error) {
            setCopilotError(error instanceof Error ? error.message : 'Could not move lead stage.');
        } finally {
            setActionLoading(null);
        }
    }

    return (
        <div className="space-y-8">
            <section className="overflow-hidden rounded-[32px] border border-slate-200/70 bg-white shadow-[0_25px_120px_-40px_rgba(15,23,42,0.35)]">
                <div className="relative overflow-hidden bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.22),_transparent_35%),linear-gradient(135deg,#020617_0%,#0f172a_45%,#111827_100%)] px-8 py-9 text-white sm:px-10">
                    <div className="relative z-10 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
                        <div className="max-w-3xl">
                            <div className="flex flex-wrap items-center gap-3">
                                <Badge tone="emerald">{readinessLabel}</Badge>
                                <Badge tone="blue">{bootstrap.plan} plan</Badge>
                                <Badge tone="violet">{bootstrap.tenantStatus}</Badge>
                            </div>

                            <h2 className="mt-5 text-4xl font-semibold tracking-tight sm:text-5xl">
                                {bootstrap.companyName} workspace overview
                            </h2>
                            <p className="mt-4 max-w-2xl text-base leading-7 text-slate-300 sm:text-lg">
                                A clear daily workspace for conversations, leads, orders, reports, and AI assistance so the team can understand what needs attention at a glance.
                            </p>
                        </div>

                        <div className="rounded-[28px] border border-white/10 bg-white/5 px-5 py-4 backdrop-blur">
                            <p className="text-xs font-semibold uppercase tracking-[0.25em] text-emerald-300">Current user</p>
                            <p className="mt-2 text-lg font-semibold">{bootstrap.fullName}</p>
                            <p className="mt-1 text-sm text-slate-300">
                                AI features enabled: {bootstrap.aiFeatures.length}
                            </p>
                            <p className="mt-1 text-sm text-slate-400">
                                Copilot source: {bootstrap.aiDemoConversationLabel ?? 'No live conversation'}
                            </p>
                        </div>
                    </div>
                </div>
            </section>

            <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
                <StatCard label="Workspace status" value={bootstrap.tenantStatus} help="Current subscription and lifecycle state." accent="bg-emerald-100" />
                <StatCard label="Plan" value={bootstrap.plan} help="Current package assigned to this workspace." accent="bg-blue-100" />
                <StatCard label="Branches" value={String(bootstrap.branchesCount)} help="Active business branches in the tenant." accent="bg-violet-100" />
                <StatCard label="Users" value={String(bootstrap.usersCount)} help="Team members who can access this workspace." accent="bg-amber-100" />
                <StatCard label="AI activity" value={String(bootstrap.aiInteractionsCount)} help="AI requests already logged for audit and review." accent="bg-rose-100" />
            </section>

            {metrics ? (
                <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    <StatCard label="Unread messages" value={String(metrics.unreadConversations)} help="Messages still waiting for a reply." accent="bg-emerald-100" />
                    <StatCard label="Open leads" value={String(metrics.openLeads)} help="Lead opportunities still in progress." accent="bg-blue-100" />
                    <StatCard label="Overdue tasks" value={String(metrics.overdueTasks)} help="Follow-ups that need immediate action." accent="bg-rose-100" />
                    <StatCard label="Revenue total" value={`$${metrics.revenueTotal.toFixed(2)}`} help="Order revenue currently recorded in the workspace." accent="bg-violet-100" />
                </section>
            ) : null}

            <section className="grid gap-6 xl:grid-cols-[minmax(0,1.3fr)_380px]">
                <div className="space-y-6">
                    <div className="rounded-[32px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)] sm:p-8">
                        <div className="flex flex-col gap-4 border-b border-slate-200 pb-6 sm:flex-row sm:items-end sm:justify-between">
                            <div>
                                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">AI Sales Copilot</p>
                                <h3 className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">Review the next conversation that needs action</h3>
                                <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-600">
                                    Professional copilot workflow: focus conversation, reply guidance, deal context, order readiness, and next-best action in one place.
                                </p>
                            </div>

                            <div className="flex flex-wrap items-center gap-3">
                                <Badge tone={bootstrap.aiEnabled ? 'emerald' : 'rose'}>
                                    {bootstrap.aiEnabled ? 'Enabled' : 'Disabled'}
                                </Badge>
                                <button
                                    type="button"
                                    onClick={runCopilot}
                                    disabled={copilotLoading || !bootstrap.aiEnabled}
                                    className="rounded-2xl bg-slate-950 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-400"
                                >
                                    {copilotLoading ? 'Analyzing…' : 'Run Sales Copilot'}
                                </button>
                            </div>
                        </div>

                        {copilotError ? (
                            <div className="mt-6 rounded-2xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-700">
                                {copilotError}
                            </div>
                        ) : null}

                        {!copilot && !copilotError ? (
                            <div className="mt-6 rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-5 py-6 text-sm leading-6 text-slate-500">
                                Run the copilot to analyze the most important live conversation in the workspace and surface reply, order, quote, and follow-up guidance.
                            </div>
                        ) : null}

                        {copilot && !copilot.available ? (
                            <div className="mt-6 rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-5 py-6 text-sm leading-6 text-slate-500">
                                {copilot.reason}
                            </div>
                        ) : null}

                        {copilot?.available ? (
                            <div className="mt-6 space-y-6">
                                <div className="grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_320px]">
                                    <div className="rounded-[28px] border border-slate-200 bg-slate-50/80 p-5">
                                        <div className="flex flex-wrap items-center gap-2">
                                            <Badge tone="blue">{copilot.focusConversation?.channel ?? 'Conversation'}</Badge>
                                            <Badge tone={copilot.focusConversation?.priority === 'urgent' ? 'rose' : copilot.focusConversation?.priority === 'high' ? 'amber' : 'slate'}>
                                                {copilot.focusConversation?.priority ?? 'normal'}
                                            </Badge>
                                            <Badge tone="emerald">{copilot.focusConversation?.unreadCount ?? 0} unread</Badge>
                                        </div>
                                        <h4 className="mt-4 text-2xl font-semibold text-slate-950">
                                            {copilot.focusConversation?.customerName}
                                        </h4>
                                        <p className="mt-2 text-sm text-slate-600">
                                            {copilot.copilot?.headline}
                                        </p>
                                        <div className="mt-4 rounded-2xl bg-white p-4 shadow-sm">
                                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Latest customer message</p>
                                            <p className="mt-3 text-sm leading-7 text-slate-700">
                                                {copilot.focusConversation?.latestCustomerMessage ?? 'No latest message.'}
                                            </p>
                                        </div>
                                        <div className="mt-4 flex flex-wrap gap-3">
                                            <a href={bootstrap.inboxUrl} className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800">
                                                Open Inbox
                                            </a>
                                            <a href={bootstrap.pipelineUrl} className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">
                                                Open Pipeline
                                            </a>
                                            <a href={bootstrap.ordersUrl} className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">
                                                Open Orders
                                            </a>
                                        </div>
                                        <div className="mt-4 flex flex-wrap gap-3">
                                            {bootstrap.canReplyConversations ? (
                                                <button
                                                    type="button"
                                                    onClick={sendSuggestedReply}
                                                    disabled={actionLoading === 'reply'}
                                                    className="rounded-2xl bg-emerald-500 px-4 py-2.5 text-sm font-semibold text-slate-950 hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-300"
                                                >
                                                    {actionLoading === 'reply' ? 'Sending…' : 'Send suggested reply'}
                                                </button>
                                            ) : null}
                                            {bootstrap.canMoveLeads && copilot.lead?.nextStage ? (
                                                <button
                                                    type="button"
                                                    onClick={moveLeadStage}
                                                    disabled={actionLoading === 'lead'}
                                                    className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
                                                >
                                                    {actionLoading === 'lead' ? 'Moving…' : `Move lead to ${copilot.lead.nextStage.name}`}
                                                </button>
                                            ) : null}
                                        </div>
                                    </div>

                                    <div className="space-y-4">
                                        <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Next best action</p>
                                            <p className="mt-3 text-sm font-semibold leading-6 text-slate-900">
                                                {copilot.copilot?.nextBestAction}
                                            </p>
                                            <p className="mt-3 text-sm text-slate-500">
                                                {copilot.copilot?.followUpRecommendation}
                                            </p>
                                        </div>
                                        <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Deal context</p>
                                            <div className="mt-3 space-y-2 text-sm text-slate-600">
                                                <p><span className="font-semibold text-slate-900">Lead:</span> {copilot.lead?.title ?? 'No linked lead'}</p>
                                                <p><span className="font-semibold text-slate-900">Stage:</span> {copilot.lead?.stage ?? 'N/A'}</p>
                                                <p><span className="font-semibold text-slate-900">Quote:</span> {copilot.quote?.quoteNumber ?? 'No quote yet'}</p>
                                                <p><span className="font-semibold text-slate-900">Order:</span> {copilot.order?.orderNumber ?? 'No order yet'}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="grid gap-4 xl:grid-cols-3">
                                    <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                        <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Reply suggestion</p>
                                        <p className="mt-3 text-sm font-semibold text-slate-900">
                                            {formatIntent(copilot.replySuggestion?.detected_intent ?? 'unclear')}
                                        </p>
                                        <p className="mt-2 text-sm text-slate-500">
                                            Confidence: {copilot.replySuggestion?.confidence !== null && copilot.replySuggestion?.confidence !== undefined
                                                ? `${Math.round(copilot.replySuggestion.confidence * 100)}%`
                                                : 'N/A'}
                                        </p>
                                        <div className="mt-4 rounded-2xl bg-slate-50 p-4 text-sm leading-7 text-slate-700">
                                            {copilot.replySuggestion?.reply_text}
                                        </div>
                                    </div>

                                    <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                        <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Order readiness</p>
                                        <div className="mt-3 flex flex-wrap gap-2">
                                            <Badge tone={copilot.orderDraft?.ready_to_create ? 'emerald' : 'amber'}>
                                                {copilot.orderDraft?.ready_to_create ? 'Ready to create' : 'Needs more detail'}
                                            </Badge>
                                            <Badge tone={copilot.orderDraft?.order_signal_detected ? 'blue' : 'slate'}>
                                                {copilot.orderDraft?.order_signal_detected ? 'Order signal detected' : 'No order signal'}
                                            </Badge>
                                        </div>
                                        <div className="mt-4 space-y-3">
                                            {(copilot.orderDraft?.items ?? []).map((item) => (
                                                <div key={`${item.product_name}-${item.quantity}`} className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-700">
                                                    <p className="font-semibold text-slate-900">{item.product_name}</p>
                                                    <p className="mt-1">Qty {item.quantity} · {item.unit_price_formatted} · stock {item.stock_quantity}</p>
                                                </div>
                                            ))}
                                            {(!copilot.orderDraft?.items || copilot.orderDraft.items.length === 0) ? (
                                                <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-500">
                                                    No order items confidently extracted yet.
                                                </div>
                                            ) : null}
                                        </div>
                                        <div className="mt-4 flex flex-wrap gap-3">
                                            {bootstrap.canManageQuotes ? (
                                                <button
                                                    type="button"
                                                    onClick={createQuote}
                                                    disabled={actionLoading === 'quote' || !(copilot.orderDraft?.items?.length)}
                                                    className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
                                                >
                                                    {actionLoading === 'quote' ? 'Creating quote…' : 'Create quote'}
                                                </button>
                                            ) : null}
                                            {bootstrap.canManageOrders ? (
                                                <button
                                                    type="button"
                                                    onClick={createOrder}
                                                    disabled={actionLoading === 'order' || !copilot.orderDraft?.ready_to_create}
                                                    className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-300"
                                                >
                                                    {actionLoading === 'order' ? 'Creating order…' : 'Create order now'}
                                                </button>
                                            ) : null}
                                        </div>
                                    </div>

                                    <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                        <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Risk and warnings</p>
                                        <div className="mt-4 space-y-2">
                                            {(copilot.copilot?.riskFlags ?? []).length > 0 ? (
                                                (copilot.copilot?.riskFlags ?? []).map((warning) => (
                                                    <div key={warning} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
                                                        {warning}
                                                    </div>
                                                ))
                                            ) : (
                                                <div className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-500">
                                                    No major risks detected in the current review.
                                                </div>
                                            )}
                                            {(copilot.orderDraft?.missing_fields ?? []).length > 0 ? (
                                                <div className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                                                    Missing fields: {copilot.orderDraft?.missing_fields.join(', ').replaceAll('_', ' ')}
                                                </div>
                                            ) : null}
                                        </div>
                                    </div>
                                </div>

                                <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
                                    <div className="flex items-center justify-between gap-3">
                                        <div>
                                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Recent timeline</p>
                                            <h4 className="mt-2 text-lg font-semibold text-slate-950">What changed most recently</h4>
                                        </div>
                                        <div className="flex flex-wrap gap-2">
                                            <Badge tone="blue">{copilot.replySuggestion?.provider ?? 'AI'}</Badge>
                                            <Badge tone="amber">{copilot.replySuggestion?.prompt_version ?? 'copilot'}</Badge>
                                        </div>
                                    </div>
                                    <div className="mt-4 space-y-3">
                                        {(copilot.focusConversation?.recentTimeline ?? []).map((item, index) => (
                                            <div key={`${item.time}-${index}`} className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-700">
                                                <div className="flex items-center justify-between gap-3">
                                                    <span className="font-semibold text-slate-900">{item.direction}</span>
                                                    <span className="text-xs text-slate-500">{item.time ?? 'Now'}</span>
                                                </div>
                                                <p className="mt-2 leading-6">{item.text}</p>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        ) : null}
                    </div>

                    <aside className="space-y-6">
                        <section className="rounded-[32px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <div className="flex items-center justify-between gap-3">
                                <div>
                                    <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">AI readiness</p>
                                    <h3 className="mt-2 text-xl font-semibold text-slate-950">Workspace configuration</h3>
                                </div>
                                <Badge tone={bootstrap.aiKnowledgeCount > 0 ? 'emerald' : 'amber'}>
                                    {bootstrap.aiKnowledgeCount > 0 ? 'Grounded' : 'Needs snippets'}
                                </Badge>
                            </div>

                            <div className="mt-5 space-y-3">
                                <div className="rounded-2xl border border-slate-200 p-4">
                                    <p className="text-sm font-medium text-slate-900">Knowledge snippets</p>
                                    <p className="mt-1 text-sm text-slate-500">
                                        {bootstrap.aiKnowledgeCount} policy or brand snippets are available for AI grounding.
                                    </p>
                                </div>
                                <div className="rounded-2xl border border-slate-200 p-4">
                                    <p className="text-sm font-medium text-slate-900">Enabled feature keys</p>
                                    <div className="mt-3 flex flex-wrap gap-2">
                                        {bootstrap.aiFeatures.length > 0 ? (
                                            bootstrap.aiFeatures.map((feature) => (
                                                <Badge key={feature} tone="slate">
                                                    {feature.replaceAll('_', ' ')}
                                                </Badge>
                                            ))
                                        ) : (
                                            <p className="text-sm text-slate-500">No AI features enabled yet.</p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </section>

                        <section className="rounded-[32px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">Product roadmap</p>
                            <div className="mt-5 space-y-4">
                                {moduleCards.map((card) => (
                                    <div key={card.title} className="rounded-2xl border border-slate-200 p-4">
                                        <div className="flex items-center justify-between gap-3">
                                            <p className="font-semibold text-slate-900">{card.title}</p>
                                            <Badge tone={card.status === 'Live' ? 'emerald' : card.status === 'Ready' ? 'blue' : 'amber'}>
                                                {card.status}
                                            </Badge>
                                        </div>
                                        <p className="mt-2 text-sm leading-6 text-slate-500">{card.description}</p>
                                    </div>
                                ))}
                            </div>
                        </section>
                    </aside>
                </div>
            </section>
        </div>
    );
}

export type { DashboardBootstrap };
