import { createFileRoute } from "@tanstack/react-router";
import { useState, useRef, useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { DashboardLayout } from "@/components/dashboard-layout";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Progress } from "@/components/ui/progress";
import { Slider } from "@/components/ui/slider";
import { DashboardHeader } from "@/components/dashboard/widgets";
import {
  initialChat,
  promptHistory,
  savedPrompts,
  aiSuggestionsLong,
  type ChatMessage,
} from "@/lib/ai-data";
import {
  analyzeAiComplianceFn,
  chatAiCopilotFn,
  generateAiContentFn,
  rewriteAiContentFn,
  translateAiContentFn,
} from "@/lib/ai/ai.functions";
import {
  AI_LANGUAGES,
  type AiChannel,
  type AiLanguage,
  type AiRiskLevel,
  type AiTone,
  type ComplianceAnalysis,
  type GeneratedContent,
  type TranslationOutput,
} from "@/lib/ai/engine";
import {
  Sparkles,
  Send,
  Wand2,
  Languages,
  ShieldCheck,
  History,
  Bookmark,
  Pin,
  Copy,
  RefreshCw,
  ThumbsUp,
  ThumbsDown,
  Search,
  Plus,
  Mic,
  Lightbulb,
  Zap,
  FileText,
  ArrowRight,
  Settings2,
  Bot,
  User as UserIcon,
  AlertTriangle,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { requireRole } from "@/lib/auth/guards";

export const Route = createFileRoute("/ai-studio")({
  beforeLoad: ({ context, location }) => requireRole(context, location, "advertiser", "superadmin"),
  head: () => ({
    meta: [
      { title: "AI Studio — VotersAlert" },
      {
        name: "description",
        content: "Generate, translate and optimise political campaign content with AI.",
      },
    ],
  }),
  component: AIStudio,
});

function AIStudio() {
  return (
    <DashboardLayout>
      <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-[1600px] mx-auto">
        <DashboardHeader
          eyebrow={
            <>
              <Sparkles className="h-3 w-3" />
              <span>AI-native workspace · 8,420 / 10,000 credits</span>
            </>
          }
          title="AI Studio"
          subtitle="Draft, translate, and refine multi-channel political content with compliant AI."
          actions={
            <>
              <Button variant="outline" size="sm" className="gap-1.5">
                <Settings2 className="h-3.5 w-3.5" /> Model
              </Button>
              <Button size="sm" className="gap-1.5">
                <Plus className="h-3.5 w-3.5" /> New session
              </Button>
            </>
          }
        />

        <Tabs defaultValue="chat" className="space-y-4">
          <TabsList className="grid w-full grid-cols-2 sm:grid-cols-5 max-w-3xl">
            <TabsTrigger value="chat" className="gap-1.5">
              <Bot className="h-3.5 w-3.5" /> Chat
            </TabsTrigger>
            <TabsTrigger value="generate" className="gap-1.5">
              <Wand2 className="h-3.5 w-3.5" /> Generate
            </TabsTrigger>
            <TabsTrigger value="translate" className="gap-1.5">
              <Languages className="h-3.5 w-3.5" /> Translate
            </TabsTrigger>
            <TabsTrigger value="compliance" className="gap-1.5">
              <ShieldCheck className="h-3.5 w-3.5" /> Compliance
            </TabsTrigger>
            <TabsTrigger value="suggestions" className="gap-1.5">
              <Lightbulb className="h-3.5 w-3.5" /> Suggestions
            </TabsTrigger>
          </TabsList>

          <TabsContent value="chat" className="m-0">
            <ChatWorkspace />
          </TabsContent>
          <TabsContent value="generate" className="m-0">
            <GeneratorWorkspace />
          </TabsContent>
          <TabsContent value="translate" className="m-0">
            <TranslationWorkspace />
          </TabsContent>
          <TabsContent value="compliance" className="m-0">
            <ComplianceAiWorkspace />
          </TabsContent>
          <TabsContent value="suggestions" className="m-0">
            <SuggestionsWorkspace />
          </TabsContent>
        </Tabs>
      </div>
    </DashboardLayout>
  );
}

/* ----------------------------- CHAT ----------------------------- */

function ChatWorkspace() {
  const [messages, setMessages] = useState<ChatMessage[]>(initialChat);
  const [input, setInput] = useState("");
  const [filter, setFilter] = useState("");
  const endRef = useRef<HTMLDivElement>(null);
  const chatMutation = useMutation({
    mutationFn: (prompt: string) =>
      chatAiCopilotFn({ data: { prompt } }) as Promise<{ reply: string }>,
  });

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const send = async (value?: string) => {
    const v = (value ?? input).trim();
    if (!v) return;
    const now = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    setMessages((m) => [
      ...m,
      { id: crypto.randomUUID(), role: "user", content: v, timestamp: now },
    ]);
    setInput("");
    try {
      const response = await chatMutation.mutateAsync(v);
      setMessages((m) => [
        ...m,
        {
          id: crypto.randomUUID(),
          role: "assistant",
          content: response.reply,
          timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
          tokens: Math.round(response.reply.length / 4),
        },
      ]);
    } catch (err) {
      setMessages((m) => [
        ...m,
        {
          id: crypto.randomUUID(),
          role: "assistant",
          content: err instanceof Error ? err.message : "AI Copilot could not process that prompt.",
          timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
        },
      ]);
    }
  };

  const filtered = promptHistory.filter((p) =>
    p.title.toLowerCase().includes(filter.toLowerCase()),
  );

  return (
    <div className="grid lg:grid-cols-[280px_1fr_280px] gap-4">
      {/* History */}
      <Card className="hidden lg:flex flex-col h-[calc(100vh-280px)] min-h-[600px]">
        <CardHeader className="pb-2 space-y-2">
          <div className="flex items-center justify-between">
            <CardTitle className="text-sm flex items-center gap-1.5">
              <History className="h-3.5 w-3.5" /> History
            </CardTitle>
            <Button size="icon" variant="ghost" className="h-7 w-7">
              <Plus className="h-3.5 w-3.5" />
            </Button>
          </div>
          <div className="relative">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
            <Input
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              placeholder="Search prompts"
              className="h-7 pl-7 text-xs"
            />
          </div>
        </CardHeader>
        <ScrollArea className="flex-1">
          <div className="px-2 pb-3 space-y-1">
            {filtered.map((p) => (
              <button
                key={p.id}
                className="w-full text-left rounded-md px-2 py-2 hover:bg-muted/60 transition-colors group"
              >
                <div className="flex items-start gap-2">
                  {p.pinned && <Pin className="h-3 w-3 mt-0.5 text-primary shrink-0" />}
                  <div className="min-w-0 flex-1">
                    <div className="text-xs font-medium truncate">{p.title}</div>
                    <div className="text-[10px] text-muted-foreground truncate">{p.preview}</div>
                    <div className="mt-1 flex items-center gap-1.5">
                      <span className="text-[9px] text-muted-foreground">{p.timestamp}</span>
                      {p.channel && (
                        <Badge variant="secondary" className="h-3 px-1 text-[8px]">
                          {p.channel}
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </ScrollArea>
      </Card>

      {/* Conversation */}
      <Card className="flex flex-col h-[calc(100vh-280px)] min-h-[600px]">
        <CardHeader className="pb-3 border-b">
          <div className="flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 min-w-0">
              <div className="h-8 w-8 rounded-lg bg-gradient-to-br from-primary to-accent flex items-center justify-center shrink-0">
                <Sparkles className="h-4 w-4 text-white" />
              </div>
              <div className="min-w-0">
                <CardTitle className="text-sm truncate">Lagos rally — WhatsApp draft</CardTitle>
                <div className="text-[10px] text-muted-foreground">
                  Gemini 3 Flash · 184 tokens used
                </div>
              </div>
            </div>
            <div className="flex items-center gap-1">
              <Button size="sm" variant="outline" className="h-7 text-xs gap-1">
                <Bookmark className="h-3 w-3" /> Save
              </Button>
            </div>
          </div>
        </CardHeader>

        <ScrollArea className="flex-1">
          <div className="p-4 space-y-4">
            {messages.map((m) => (
              <ChatBubble key={m.id} m={m} />
            ))}
            <div ref={endRef} />
          </div>
        </ScrollArea>

        <div className="border-t p-3 space-y-2">
          <div className="flex flex-wrap gap-1.5">
            {["Make it shorter", "Translate to Hausa", "Add emoji CTA", "Check compliance"].map(
              (q) => (
                <button
                  key={q}
                  onClick={() => send(q)}
                  className="text-[11px] rounded-full border border-border bg-background px-2.5 py-1 hover:bg-accent hover:text-accent-foreground transition-colors"
                >
                  {q}
                </button>
              ),
            )}
          </div>
          <div className="flex items-end gap-2">
            <Textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Ask the AI to draft, translate, or audit any campaign asset…"
              className="min-h-[52px] max-h-40 resize-none text-sm"
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  send();
                }
              }}
            />
            <div className="flex flex-col gap-1">
              <Button size="icon" variant="outline" className="h-8 w-8">
                <Mic className="h-3.5 w-3.5" />
              </Button>
              <Button size="icon" className="h-8 w-8" onClick={() => send()}>
                <Send className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>
          <div className="text-[10px] text-muted-foreground">
            Shift + Enter for new line · responses are advisory.
          </div>
        </div>
      </Card>

      {/* Saved + context */}
      <div className="hidden lg:flex flex-col gap-4 h-[calc(100vh-280px)] min-h-[600px]">
        <Card className="flex-1 flex flex-col min-h-0">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm flex items-center gap-1.5">
              <Bookmark className="h-3.5 w-3.5" /> Saved prompts
            </CardTitle>
          </CardHeader>
          <ScrollArea className="flex-1">
            <div className="px-3 pb-3 space-y-2">
              {savedPrompts.map((p) => (
                <button
                  key={p.id}
                  className="w-full text-left rounded-lg border border-border bg-background/60 p-2.5 hover:border-primary/40 hover:bg-muted/40 transition-colors"
                >
                  <div className="text-xs font-medium">{p.title}</div>
                  <div className="text-[10px] text-muted-foreground mt-0.5 line-clamp-2">
                    {p.preview}
                  </div>
                  <div className="mt-1.5 flex items-center justify-between">
                    <span className="text-[9px] text-muted-foreground">{p.timestamp}</span>
                    {p.channel && (
                      <Badge variant="secondary" className="h-3 px-1 text-[8px]">
                        {p.channel}
                      </Badge>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </ScrollArea>
        </Card>

        <Card className="bg-gradient-to-br from-primary/5 via-accent/5 to-transparent border-primary/20">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm flex items-center gap-1.5">
              <Zap className="h-3.5 w-3.5 text-primary" /> Session
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-xs">
            <Row label="Model" value="Gemini 3 Flash" />
            <Row label="Tokens" value="184 / 4,096" />
            <Row label="Cost" value="₦12.40" />
            <Separator />
            <div className="text-[10px] text-muted-foreground">
              Compliance checks run automatically before any output is exported to a campaign.
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-medium tabular-nums">{value}</span>
    </div>
  );
}

function ChatBubble({ m }: { m: ChatMessage }) {
  const isUser = m.role === "user";
  return (
    <div className={cn("flex gap-3", isUser && "flex-row-reverse")}>
      <div
        className={cn(
          "h-8 w-8 rounded-lg flex items-center justify-center shrink-0",
          isUser ? "bg-muted" : "bg-gradient-to-br from-primary to-accent",
        )}
      >
        {isUser ? (
          <UserIcon className="h-4 w-4 text-foreground" />
        ) : (
          <Sparkles className="h-4 w-4 text-white" />
        )}
      </div>
      <div className={cn("max-w-[80%] space-y-1.5", isUser && "items-end flex flex-col")}>
        <div
          className={cn(
            "rounded-2xl px-3.5 py-2.5 text-sm leading-relaxed whitespace-pre-wrap",
            isUser ? "bg-primary text-primary-foreground rounded-br-sm" : "bg-muted rounded-bl-sm",
          )}
        >
          {m.content}
        </div>
        <div className="flex items-center gap-1 px-1">
          <span className="text-[10px] text-muted-foreground">
            {m.timestamp}
            {m.tokens ? ` · ${m.tokens} tok` : ""}
          </span>
          {!isUser && (
            <>
              <Button size="icon" variant="ghost" className="h-6 w-6">
                <Copy className="h-3 w-3" />
              </Button>
              <Button size="icon" variant="ghost" className="h-6 w-6">
                <RefreshCw className="h-3 w-3" />
              </Button>
              <Button size="icon" variant="ghost" className="h-6 w-6">
                <ThumbsUp className="h-3 w-3" />
              </Button>
              <Button size="icon" variant="ghost" className="h-6 w-6">
                <ThumbsDown className="h-3 w-3" />
              </Button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* --------------------------- GENERATOR --------------------------- */

function GeneratorWorkspace() {
  const [tone, setTone] = useState<AiTone>("energetic");
  const [channel, setChannel] = useState<AiChannel>("whatsapp");
  const [language, setLanguage] = useState<AiLanguage>("english");
  const [variants, setVariants] = useState(3);
  const [includeEmoji, setIncludeEmoji] = useState(true);
  const [brief, setBrief] = useState(
    "Mobilise first-time voters in Lagos for Saturday rally at Tafawa Balewa Square. Free shuttle. Hope Coalition PAC.",
  );
  const [audience, setAudience] = useState("Lagos voters aged 18–34");
  const generateMutation = useMutation({
    mutationFn: () =>
      generateAiContentFn({
        data: {
          brief,
          audience,
          channel,
          tone,
          variants,
          language,
          includeEmoji,
          includeOptOut: channel === "sms" || channel === "whatsapp",
        },
      }) as Promise<GeneratedContent[]>,
  });
  const outputs = generateMutation.data ?? [];

  return (
    <div className="grid lg:grid-cols-2 gap-4">
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Wand2 className="h-4 w-4 text-primary" /> Content generator
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <Field label="Channel">
              <Select value={channel} onValueChange={(value) => setChannel(value as AiChannel)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="whatsapp">WhatsApp</SelectItem>
                  <SelectItem value="sms">SMS</SelectItem>
                  <SelectItem value="voice">Voice IVR</SelectItem>
                  <SelectItem value="facebook">Facebook Ad</SelectItem>
                  <SelectItem value="google">Google Display</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label="Tone">
              <Select value={tone} onValueChange={(value) => setTone(value as AiTone)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="energetic">Energetic</SelectItem>
                  <SelectItem value="hopeful">Hopeful</SelectItem>
                  <SelectItem value="urgent">Urgent</SelectItem>
                  <SelectItem value="formal">Formal</SelectItem>
                  <SelectItem value="conversational">Conversational</SelectItem>
                </SelectContent>
              </Select>
            </Field>
          </div>

          <Field label="Campaign brief">
            <Textarea
              value={brief}
              onChange={(e) => setBrief(e.target.value)}
              className="min-h-[100px] text-sm"
            />
          </Field>

          <div className="grid grid-cols-2 gap-3">
            <Field label="Audience">
              <Input
                value={audience}
                onChange={(e) => setAudience(e.target.value)}
                className="h-9"
              />
            </Field>
            <Field label="Variants">
              <div className="flex items-center gap-3 pt-2">
                <Slider
                  value={[variants]}
                  onValueChange={(value) => setVariants(value[0] ?? 1)}
                  max={6}
                  min={1}
                  step={1}
                />
                <span className="text-xs tabular-nums w-4">{variants}</span>
              </div>
            </Field>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <Field label="Language">
              <Select value={language} onValueChange={(value) => setLanguage(value as AiLanguage)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {AI_LANGUAGES.map((l) => (
                    <SelectItem key={l} value={l}>
                      {languageLabel(l)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <label className="flex items-center gap-2 rounded-md border p-3 text-xs">
              <Checkbox
                checked={includeEmoji}
                onCheckedChange={(value) => setIncludeEmoji(Boolean(value))}
              />
              Add emoji where channel-safe
            </label>
          </div>

          <div className="flex flex-wrap gap-2">
            {["Add emoji", "Include CTA", "Use Pidgin", "Compliance-safe"].map((t) => (
              <Badge
                key={t}
                variant="secondary"
                className="cursor-pointer hover:bg-primary hover:text-primary-foreground transition-colors"
              >
                {t}
              </Badge>
            ))}
          </div>

          <Button
            onClick={() => generateMutation.mutate()}
            disabled={generateMutation.isPending}
            className="w-full gap-2"
          >
            {generateMutation.isPending ? (
              <RefreshCw className="h-4 w-4 animate-spin" />
            ) : (
              <Sparkles className="h-4 w-4" />
            )}
            {generateMutation.isPending ? "Generating…" : "Generate content"}
          </Button>
          {generateMutation.isError && (
            <div className="text-xs text-destructive">
              {generateMutation.error instanceof Error
                ? generateMutation.error.message
                : "Generation failed."}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3 flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base flex items-center gap-2">
            <FileText className="h-4 w-4 text-primary" /> Output
          </CardTitle>
          <div className="flex items-center gap-1">
            <Badge
              variant="outline"
              className="text-[10px] bg-success/10 text-success border-success/30 gap-1"
            >
              <ShieldCheck className="h-3 w-3" /> Compliant
            </Badge>
            <Button size="sm" variant="ghost" className="h-7 text-xs gap-1">
              <Copy className="h-3 w-3" /> Copy
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {outputs.length ? (
            <div className="space-y-3">
              {outputs.map((output) => (
                <div key={output.id} className="rounded-lg border bg-muted/30 p-3 space-y-3">
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <div className="text-xs font-semibold">{output.headline}</div>
                      <div className="mt-2 text-sm whitespace-pre-wrap leading-relaxed">
                        {output.message}
                      </div>
                    </div>
                    <RiskBadge
                      level={output.compliance.riskLevel}
                      score={output.compliance.score}
                    />
                  </div>
                  <div className="grid grid-cols-3 gap-2 text-center">
                    <Stat label="Length" value={String(output.characterCount)} hint="chars" />
                    <Stat
                      label="Read time"
                      value={`0:${String(output.readTimeSeconds).padStart(2, "0")}`}
                      hint="seconds"
                    />
                    <Stat label="CTA" value={output.cta.split(" ")[0]} hint="ready" />
                  </div>
                  <Separator />
                  <div className="space-y-1">
                    {output.compliance.rewriteSuggestions.slice(0, 2).map((s) => (
                      <div
                        key={s}
                        className="flex items-start gap-2 text-[11px] text-muted-foreground"
                      >
                        <Wand2 className="h-3 w-3 mt-0.5 text-primary shrink-0" />
                        <span>{s}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center text-center py-16 text-muted-foreground">
              <Sparkles className="h-8 w-8 mb-2 opacity-40" />
              <div className="text-sm">Configure your brief and generate to see output here.</div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1.5">
      <label className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">
        {label}
      </label>
      {children}
    </div>
  );
}

function Stat({ label, value, hint }: { label: string; value: string; hint: string }) {
  return (
    <div className="rounded-md border bg-background/60 p-2">
      <div className="text-[10px] text-muted-foreground">{label}</div>
      <div className="text-sm font-semibold tabular-nums">{value}</div>
      <div className="text-[9px] text-muted-foreground">{hint}</div>
    </div>
  );
}

const riskTone: Record<AiRiskLevel, string> = {
  low: "bg-success/10 text-success border-success/30",
  medium: "bg-warning/10 text-warning-foreground border-warning/30",
  high: "bg-orange-500/10 text-orange-600 dark:text-orange-400 border-orange-500/30",
  critical: "bg-destructive/10 text-destructive border-destructive/30",
};

function RiskBadge({ level, score }: { level: AiRiskLevel; score: number }) {
  return (
    <Badge variant="outline" className={cn("text-[10px] shrink-0", riskTone[level])}>
      {level} · {score}
    </Badge>
  );
}

function languageLabel(language: AiLanguage) {
  return { english: "English", hausa: "Hausa", yoruba: "Yoruba", igbo: "Igbo", pidgin: "Pidgin" }[
    language
  ];
}

/* --------------------------- TRANSLATE --------------------------- */

function TranslationWorkspace() {
  const [source, setSource] = useState(
    "Lagos, your voice matters! Join us this Saturday at Tafawa Balewa Square, 10AM, for the Hope Rally. Free shuttle from Yaba, Ikeja & Surulere. Reply STOP to opt out.",
  );
  const [targets, setTargets] = useState<AiLanguage[]>([
    "english",
    "hausa",
    "yoruba",
    "igbo",
    "pidgin",
  ]);
  const translateMutation = useMutation({
    mutationFn: () =>
      translateAiContentFn({ data: { text: source, targets } }) as Promise<TranslationOutput[]>,
  });
  const translations = translateMutation.data ?? [];
  const toggleTarget = (language: AiLanguage) =>
    setTargets((prev) =>
      prev.includes(language) ? prev.filter((item) => item !== language) : [...prev, language],
    );

  return (
    <div className="grid lg:grid-cols-[1fr_2fr] gap-4">
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Languages className="h-4 w-4 text-primary" /> Source
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <Textarea
            value={source}
            onChange={(e) => setSource(e.target.value)}
            className="min-h-[180px] text-sm"
          />
          <div className="flex items-center justify-between text-[11px] text-muted-foreground">
            <span>Auto-detected source · {source.length} chars</span>
            <span>Compliance tokens preserved</span>
          </div>
          <div className="space-y-2">
            <div className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
              Target languages
            </div>
            <div className="flex flex-wrap gap-1.5">
              {AI_LANGUAGES.map((l) => (
                <Badge
                  key={l}
                  variant={targets.includes(l) ? "default" : "outline"}
                  className="cursor-pointer"
                  onClick={() => toggleTarget(l)}
                >
                  {languageLabel(l)}
                </Badge>
              ))}
            </div>
          </div>
          <Button
            className="w-full gap-2"
            onClick={() => translateMutation.mutate()}
            disabled={translateMutation.isPending || targets.length === 0}
          >
            {translateMutation.isPending ? (
              <RefreshCw className="h-4 w-4 animate-spin" />
            ) : (
              <Sparkles className="h-4 w-4" />
            )}
            Translate
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3 flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">Translations</CardTitle>
          <Badge variant="secondary" className="text-[10px]">
            {translations.length || targets.length} variants ready
          </Badge>
        </CardHeader>
        <CardContent className="grid sm:grid-cols-2 gap-3">
          {translations.length ? (
            translations.map((t) => (
              <div key={t.language} className="rounded-lg border bg-background/60 p-3 space-y-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-1.5">
                    <span className="text-base">🇳🇬</span>
                    <span className="text-sm font-semibold">{t.languageName}</span>
                  </div>
                  <Badge
                    variant="outline"
                    className="text-[10px] bg-success/10 text-success border-success/30"
                  >
                    {t.quality}% quality
                  </Badge>
                </div>
                <div className="text-xs leading-relaxed text-muted-foreground">{t.text}</div>
                <Progress value={t.quality} className="h-1" />
                <div className="flex items-center justify-end gap-1">
                  <Button size="sm" variant="ghost" className="h-7 text-[11px] gap-1">
                    <Copy className="h-3 w-3" /> Copy
                  </Button>
                  <Button size="sm" className="h-7 text-[11px] gap-1">
                    Use <ArrowRight className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            ))
          ) : (
            <div className="sm:col-span-2 flex flex-col items-center justify-center text-center py-16 text-muted-foreground">
              <Languages className="h-8 w-8 mb-2 opacity-40" />
              <div className="text-sm">
                Select languages and translate to generate localized copy.
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

/* -------------------------- COMPLIANCE AI -------------------------- */

function ComplianceAiWorkspace() {
  const [text, setText] = useState(
    "Lagos, your voice matters. Join the Hope Coalition PAC rally this Saturday and make a peaceful voting plan. Reply STOP to opt out.",
  );
  const [channel, setChannel] = useState<AiChannel>("whatsapp");
  const [language, setLanguage] = useState<AiLanguage>("english");
  const analyzeMutation = useMutation({
    mutationFn: () =>
      analyzeAiComplianceFn({ data: { text, channel, language } }) as Promise<ComplianceAnalysis>,
  });
  const rewriteMutation = useMutation({
    mutationFn: () =>
      rewriteAiContentFn({ data: { text, channel, language } }) as Promise<{
        rewrittenText: string;
        after: ComplianceAnalysis;
      }>,
    onSuccess: (result) => setText(result.rewrittenText),
  });
  const analysis = rewriteMutation.data?.after ?? analyzeMutation.data;

  return (
    <div className="grid lg:grid-cols-[1fr_1.2fr] gap-4">
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <ShieldCheck className="h-4 w-4 text-primary" /> AI Compliance Engine
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <Field label="Channel">
              <Select value={channel} onValueChange={(value) => setChannel(value as AiChannel)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {AI_CHANNELS_FOR_UI.map((item) => (
                    <SelectItem key={item.value} value={item.value}>
                      {item.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field label="Language">
              <Select value={language} onValueChange={(value) => setLanguage(value as AiLanguage)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {AI_LANGUAGES.map((l) => (
                    <SelectItem key={l} value={l}>
                      {languageLabel(l)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
          </div>
          <Field label="Creative to validate">
            <Textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              className="min-h-[220px] text-sm"
            />
          </Field>
          <div className="flex gap-2">
            <Button
              className="flex-1 gap-2"
              onClick={() => analyzeMutation.mutate()}
              disabled={analyzeMutation.isPending}
            >
              {analyzeMutation.isPending ? (
                <RefreshCw className="h-4 w-4 animate-spin" />
              ) : (
                <ShieldCheck className="h-4 w-4" />
              )}
              Validate content
            </Button>
            <Button
              variant="outline"
              className="gap-2"
              onClick={() => rewriteMutation.mutate()}
              disabled={rewriteMutation.isPending}
            >
              <Wand2 className="h-4 w-4" /> Rewrite
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3 flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">Risk analysis</CardTitle>
          {analysis && <RiskBadge level={analysis.riskLevel} score={analysis.score} />}
        </CardHeader>
        <CardContent>
          {analysis ? (
            <div className="space-y-4">
              <div className="rounded-lg border bg-muted/30 p-3">
                <div className="flex items-center gap-2 text-sm font-medium">
                  {analysis.verdict === "approved" ? (
                    <CheckCircle2 className="h-4 w-4 text-success" />
                  ) : analysis.verdict === "blocked" ? (
                    <XCircle className="h-4 w-4 text-destructive" />
                  ) : (
                    <AlertTriangle className="h-4 w-4 text-warning-foreground" />
                  )}
                  {analysis.summary}
                </div>
                <Progress value={analysis.score} className="mt-3 h-2" />
              </div>
              <div className="grid sm:grid-cols-4 gap-2">
                {Object.entries(analysis.categories).map(([key, category]) => (
                  <Stat
                    key={key}
                    label={category.label}
                    value={String(category.score)}
                    hint={category.detected ? "detected" : "clear"}
                  />
                ))}
              </div>
              <div className="space-y-2">
                <div className="text-xs font-semibold uppercase text-muted-foreground">
                  Policy validation
                </div>
                {analysis.policyChecks.map((check) => (
                  <div
                    key={check.code}
                    className="flex items-start gap-2 rounded-md border p-2 text-xs"
                  >
                    {check.passed ? (
                      <CheckCircle2 className="h-3.5 w-3.5 text-success mt-0.5" />
                    ) : (
                      <AlertTriangle className="h-3.5 w-3.5 text-warning-foreground mt-0.5" />
                    )}
                    <div className="flex-1">
                      <span className="font-medium">
                        {check.code} · {check.title}
                      </span>
                      <div className="text-muted-foreground">{check.detail}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div className="space-y-2">
                <div className="text-xs font-semibold uppercase text-muted-foreground">
                  Rewrite suggestions
                </div>
                {analysis.rewriteSuggestions.map((suggestion) => (
                  <div
                    key={suggestion}
                    className="rounded-md border bg-background/60 p-2 text-xs text-muted-foreground"
                  >
                    {suggestion}
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center text-center py-16 text-muted-foreground">
              <ShieldCheck className="h-8 w-8 mb-2 opacity-40" />
              <div className="text-sm">
                Run validation to see moderation signals and risk scoring.
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

const AI_CHANNELS_FOR_UI: Array<{ value: AiChannel; label: string }> = [
  { value: "whatsapp", label: "WhatsApp" },
  { value: "sms", label: "SMS" },
  { value: "voice", label: "Voice IVR" },
  { value: "facebook", label: "Facebook Ad" },
  { value: "google", label: "Google Display" },
];

/* --------------------------- SUGGESTIONS --------------------------- */

function SuggestionsWorkspace() {
  const impactColor: Record<string, string> = {
    Critical: "bg-destructive/10 text-destructive border-destructive/30",
    High: "bg-primary/10 text-primary border-primary/30",
    Medium: "bg-warning/10 text-warning-foreground border-warning/30",
  };
  return (
    <div className="grid lg:grid-cols-2 gap-4">
      {aiSuggestionsLong.map((s) => (
        <Card key={s.id} className="hover:border-primary/40 transition-colors">
          <CardContent className="p-4 space-y-3">
            <div className="flex items-start justify-between gap-3">
              <div className="flex items-start gap-3 min-w-0">
                <div className="h-9 w-9 rounded-lg bg-gradient-to-br from-primary/10 to-accent/10 flex items-center justify-center shrink-0">
                  <Lightbulb className="h-4 w-4 text-primary" />
                </div>
                <div className="min-w-0">
                  <div className="text-sm font-semibold leading-tight">{s.title}</div>
                  <div className="text-xs text-muted-foreground mt-1 leading-relaxed">
                    {s.detail}
                  </div>
                </div>
              </div>
              <Badge
                variant="outline"
                className={cn("text-[10px] shrink-0", impactColor[s.impact])}
              >
                {s.impact}
              </Badge>
            </div>
            <div className="flex items-center gap-2">
              <Progress value={s.confidence * 100} className="h-1 flex-1" />
              <span className="text-[10px] text-muted-foreground tabular-nums">
                {Math.round(s.confidence * 100)}% confidence
              </span>
            </div>
            <div className="flex items-center justify-end gap-2 pt-1">
              <Button size="sm" variant="ghost" className="h-7 text-xs">
                Dismiss
              </Button>
              <Button size="sm" className="h-7 text-xs gap-1">
                Apply <ArrowRight className="h-3 w-3" />
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
