/**
 * WhatsApp Bulk Sender (Click-to-WhatsApp, FREE)
 * ------------------------------------------------
 * Workflow:
 *   1. Pick a template OR write a custom message with {{name}}-style variables.
 *   2. Pick recipients (search/filter parties or paste raw numbers).
 *   3. Hit "Start Bulk Send" — backend pre-renders each party's wa.me URL,
 *      frontend opens them one-by-one with a configurable delay.
 *   4. User clicks the green Send arrow in WhatsApp Web/desktop for each chat.
 *   5. Batch is logged to `marketing_campaigns` for the History tab.
 *
 * NO third-party API, NO Meta approval — uses the user's own WhatsApp.
 */
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Checkbox } from "@/components/ui/checkbox";
import {
    Send, Users, MessageCircle, Search, Play, Pause, Square, RefreshCw,
    CheckCircle2, AlertTriangle, Phone, Copy, X, History as HistoryIcon, Sparkles, ExternalLink, Plus,
} from "lucide-react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import AutoTransactionMessages from "@/components/AutoTransactionMessages";

const DEFAULT_DELAY_MS = 4000;
const LS_DRAFT = "rbs_wa_bulk_draft_v1";

/** Replace {{var}} placeholders for the LIVE preview. */
function interpolate(text, vars) {
    return (text || "").replace(/\{\{\s*([^}]+)\s*\}\}/g, (_, k) => {
        const key = k.trim();
        return vars[key] != null ? String(vars[key]) : `{{${key}}}`;
    });
}

export default function WhatsAppBulkSender() {
    const [tab, setTab] = useState("compose");
    const [templates, setTemplates] = useState([]);
    const [parties, setParties] = useState([]);
    const [search, setSearch] = useState("");
    const [selected, setSelected] = useState(new Set());
    const [audience, setAudience] = useState("all");      // all | customers | vendors | manual
    const [message, setMessage] = useState("");
    const [campaignName, setCampaignName] = useState("");
    const [extraVars, setExtraVars] = useState({});
    const [delayMs, setDelayMs] = useState(DEFAULT_DELAY_MS);
    const [sending, setSending] = useState(false);
    const [pausedRef, setPausedRef] = useState(false);
    const stopFlagRef = useRef(false);
    const [progress, setProgress] = useState({ current: 0, total: 0, sent: 0 });
    const [previewItems, setPreviewItems] = useState([]);
    const [history, setHistory] = useState([]);
    // v12 — AI Quick Composer (Daily Greeting + Business Tips)
    const [aiBusy, setAiBusy] = useState("");      // "" | "greeting-good-morning" | "tip-growth" | …

    const composeWithAI = async (kind, sub) => {
        const tag = `${kind}-${sub}`;
        setAiBusy(tag);
        try {
            if (kind === "greeting") {
                const { data } = await api.post("/marketing/ai-greeting", {
                    occasion: sub,
                    language: "hinglish",
                    business_name: "",
                    include_offer: false,
                });
                if (data?.message) {
                    setMessage(data.message);
                    toast.success("Greeting loaded — review then send");
                } else {
                    toast.error("AI returned empty greeting — try again");
                }
            } else if (kind === "tip") {
                const { data } = await api.post("/marketing/ai-business-tip", {
                    topic: sub,
                    language: "hinglish",
                    business_type: "general retail",
                });
                if (data?.tip) {
                    const composed = `${data.title ? `*${data.title}*\n\n` : ""}${data.tip}${data.action ? `\n\n👉 ${data.action}` : ""}`;
                    setMessage(composed);
                    toast.success("Business tip loaded — review then send");
                } else {
                    toast.error("AI returned empty tip — try again");
                }
            }
        } catch (e) {
            const detail = e?.response?.data?.detail || e?.message || "";
            toast.error(detail ? `AI generation failed: ${detail.slice(0, 100)}` : "AI generation failed — please retry");
        } finally {
            setAiBusy("");
        }
    };

    // ----- Loaders ---------------------------------------------------------
    useEffect(() => {
        api.get("/marketing/templates").then((r) => setTemplates(r.data || [])).catch(() => {});
        api.get("/parties", { params: { limit: 5000 } }).then((r) => setParties(r.data || [])).catch(() => {});
        api.get("/marketing/campaigns").then((r) => setHistory(r.data || [])).catch(() => {});

        // Restore draft
        try {
            const raw = localStorage.getItem(LS_DRAFT);
            if (raw) {
                const d = JSON.parse(raw);
                if (d.message) setMessage(d.message);
                if (d.campaignName) setCampaignName(d.campaignName);
                if (d.extraVars) setExtraVars(d.extraVars);
            }
        } catch (e) { /* ignore */ }
    }, []);

    // ----- Persist draft ---------------------------------------------------
    useEffect(() => {
        try {
            localStorage.setItem(LS_DRAFT, JSON.stringify({ message, campaignName, extraVars }));
        } catch (e) { /* ignore */ }
    }, [message, campaignName, extraVars]);

    const filteredParties = useMemo(() => {
        let list = parties;
        if (audience === "customers") list = list.filter((p) => p.type === "customer");
        else if (audience === "vendors") list = list.filter((p) => p.type === "vendor");
        // v12 — Smart segments
        else if (audience === "high-value") list = list.filter((p) => Number(p.outstanding || 0) > 10000);
        else if (audience === "due-payment") list = list.filter((p) => Number(p.outstanding || 0) > 0);
        else if (audience === "credit-balance") list = list.filter((p) => Number(p.outstanding || 0) < 0);
        if (search.trim()) {
            const q = search.toLowerCase();
            list = list.filter((p) =>
                (p.name || "").toLowerCase().includes(q) ||
                (p.phone || "").includes(q) ||
                (p.email || "").toLowerCase().includes(q));
        }
        return list;
    }, [parties, audience, search]);

    const withPhone = useMemo(() => filteredParties.filter((p) => (p.phone || "").trim()), [filteredParties]);

    const toggle = (id) => {
        setSelected((s) => {
            const n = new Set(s);
            if (n.has(id)) n.delete(id); else n.add(id);
            return n;
        });
    };

    const selectAllVisible = () => {
        setSelected(new Set(withPhone.map((p) => p.id)));
    };

    const clearSelection = () => setSelected(new Set());

    // ----- Templates -------------------------------------------------------
    const applyTemplate = (tpl) => {
        setMessage(tpl.body || "");
        if (!campaignName) setCampaignName(tpl.label || "");
        toast.success(`Loaded "${tpl.label}"`);
    };

    // ----- Detect variables in message ------------------------------------
    const detectedVars = useMemo(() => {
        const set = new Set();
        const re = /\{\{\s*([^}]+)\s*\}\}/g;
        let m;
        while ((m = re.exec(message)) !== null) set.add(m[1].trim());
        // Auto-filled by backend
        const AUTO = new Set(["name", "customer_name", "party_name", "shop_name", "company_name"]);
        return [...set].filter((v) => !AUTO.has(v));
    }, [message]);

    // ----- Preview generation ---------------------------------------------
    const buildPreview = async () => {
        if (!message.trim()) { toast.error("Message body chahiye"); return; }
        if (selected.size === 0) { toast.error("Kam se kam 1 contact select karo"); return; }
        try {
            const { data } = await api.post("/marketing/whatsapp/preview", {
                message,
                party_ids: [...selected],
                audience: "manual",
                extra_vars: extraVars,
            });
            setPreviewItems(data.items || []);
            if (data.missing_phone) {
                toast.info(`${data.missing_phone} contact ke phone nahi mile — skip honge.`);
            }
            setTab("send");
        } catch (e) {
            toast.error(e.response?.data?.detail || "Preview banane mein dikkat");
        }
    };

    // ----- Bulk send loop --------------------------------------------------
    const startBulk = async () => {
        if (previewItems.length === 0) {
            await buildPreview();
            return;
        }
        stopFlagRef.current = false;
        setPausedRef(false);
        setSending(true);
        setProgress({ current: 0, total: previewItems.length, sent: 0 });

        let sentCount = 0;
        for (let i = 0; i < previewItems.length; i++) {
            // Honour pause/stop flags
            while (pausedRef && !stopFlagRef.current) await new Promise((r) => setTimeout(r, 300));
            if (stopFlagRef.current) break;

            const it = previewItems[i];
            // Open in a NEW WHATSAPP TAB — `noopener` so user can close fast
            try {
                window.open(it.wa_url, `wa_${i}`, "noopener,noreferrer");
                sentCount++;
            } catch (e) {
                // Popup blocker — show user a manual fallback link
                toast.error(`Popup blocker stop kar raha — ${it.name} ke liye manually click karo`);
            }
            setProgress({ current: i + 1, total: previewItems.length, sent: sentCount });
            // Delay between opens so user can hit "Send" in each tab
            if (i < previewItems.length - 1) {
                await new Promise((r) => setTimeout(r, delayMs));
            }
        }

        setSending(false);
        toast.success(`${sentCount} chats opened ✅`);
        // Log batch
        try {
            await api.post("/marketing/whatsapp/log-batch", {
                campaign_name: campaignName || "Click-to-WhatsApp Batch",
                message,
                party_ids: previewItems.map((p) => p.party_id),
                sent_count: sentCount,
                audience: "manual",
            });
            const { data: h } = await api.get("/marketing/campaigns");
            setHistory(h || []);
        } catch (e) { /* logging failure non-fatal */ }
    };

    const togglePause = () => setPausedRef((p) => !p);
    const stopBulk = () => { stopFlagRef.current = true; setPausedRef(false); setSending(false); };

    // ----- Live preview for first selected contact ------------------------
    const livePreview = useMemo(() => {
        const first = parties.find((p) => selected.has(p.id));
        const vars = {
            name: first?.name || "Ramesh Kumar",
            customer_name: first?.name || "Ramesh Kumar",
            shop_name: "REGAL MARKETING",
            ...extraVars,
        };
        return interpolate(message, vars);
    }, [message, parties, selected, extraVars]);

    const selectedCount = selected.size;

    return (
        <div className="space-y-5" data-testid="whatsapp-bulk-page">
            <header>
                <div className="text-[10px] uppercase tracking-[0.2em] text-emerald-500 font-semibold">Auto Transaction Message Center</div>
                <h1 className="font-display text-3xl font-bold flex items-center gap-2">
                    <MessageCircle className="h-7 w-7 text-emerald-600" />
                    Auto Transaction Message
                    <span className="text-base text-muted-foreground font-normal">— WhatsApp Bulk Sender</span>
                </h1>
                <p className="text-sm text-muted-foreground mt-1">
                    Configure automatic transaction messaging for WhatsApp using existing communication infrastructure. License + Super Admin gated.
                </p>
            </header>

            {/* v12.38 — Auto Transaction Message configuration (gated; renders only when platform flag + license active for current user) */}
            <AutoTransactionMessages />

            {/* Below: existing manual Bulk Send workflow — kept untouched for one-off greetings + campaigns */}
            <div className="border-t border-border/60 pt-5">
                <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground font-semibold mb-1">Manual Bulk Send</div>
                <p className="text-xs text-muted-foreground mb-3">
                    Click-to-WhatsApp — koi paid API nahi, aapke phone ke WhatsApp se hi send hota hai. Approval ki zarurat nahi.
                </p>
            </div>

            <Tabs value={tab} onValueChange={setTab} className="w-full">
                <TabsList className="grid w-full grid-cols-3" data-testid="wa-tabs">
                    <TabsTrigger value="compose" data-testid="wa-tab-compose">1. Compose</TabsTrigger>
                    <TabsTrigger value="send" data-testid="wa-tab-send">2. Send</TabsTrigger>
                    <TabsTrigger value="history" data-testid="wa-tab-history">History</TabsTrigger>
                </TabsList>

                {/* =========== TAB 1: Compose =========== */}
                <TabsContent value="compose" className="mt-4">
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                        {/* Left: Templates + Message editor */}
                        <Card className="lg:col-span-2">
                            <CardHeader className="pb-3">
                                <CardTitle className="flex items-center gap-2 text-base">
                                    <Sparkles className="h-4 w-4 text-amber-500" /> Compose Message
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {/* v12 — AI-powered one-tap composers (Vyapar parity: Daily Greeting + Business Tips) */}
                                <div className="rounded-md border border-dashed border-emerald-500/40 bg-emerald-500/5 p-3">
                                    <div className="flex items-center gap-2 mb-2">
                                        <Sparkles className="h-3.5 w-3.5 text-emerald-600" />
                                        <span className="text-[11px] font-semibold uppercase tracking-wider text-emerald-700 dark:text-emerald-400">AI Quick Composer</span>
                                    </div>
                                    <div className="flex flex-wrap gap-1.5">
                                        <Button size="sm" variant="outline" className="h-7 text-[11px] border-emerald-300 text-emerald-700 hover:bg-emerald-50" onClick={() => composeWithAI("greeting", "good-morning")} disabled={aiBusy} data-testid="ai-greet-morning">{aiBusy === "greeting-good-morning" ? "..." : "Good Morning"}</Button>
                                        <Button size="sm" variant="outline" className="h-7 text-[11px] border-emerald-300 text-emerald-700 hover:bg-emerald-50" onClick={() => composeWithAI("greeting", "festival")} disabled={aiBusy} data-testid="ai-greet-festival">{aiBusy === "greeting-festival" ? "..." : "Festival Wish"}</Button>
                                        <Button size="sm" variant="outline" className="h-7 text-[11px] border-emerald-300 text-emerald-700 hover:bg-emerald-50" onClick={() => composeWithAI("greeting", "monday-motivation")} disabled={aiBusy} data-testid="ai-greet-monday">{aiBusy === "greeting-monday-motivation" ? "..." : "Monday Motivation"}</Button>
                                        <Button size="sm" variant="outline" className="h-7 text-[11px] border-emerald-300 text-emerald-700 hover:bg-emerald-50" onClick={() => composeWithAI("greeting", "thank-you")} disabled={aiBusy} data-testid="ai-greet-thanks">{aiBusy === "greeting-thank-you" ? "..." : "Thank You"}</Button>
                                        <span className="w-full mt-1 flex flex-wrap gap-1.5">
                                            <Button size="sm" variant="outline" className="h-7 text-[11px] border-amber-300 text-amber-700 hover:bg-amber-50" onClick={() => composeWithAI("tip", "growth")} disabled={aiBusy} data-testid="ai-tip-growth">{aiBusy === "tip-growth" ? "..." : "💡 Growth Tip"}</Button>
                                            <Button size="sm" variant="outline" className="h-7 text-[11px] border-amber-300 text-amber-700 hover:bg-amber-50" onClick={() => composeWithAI("tip", "finance")} disabled={aiBusy} data-testid="ai-tip-finance">{aiBusy === "tip-finance" ? "..." : "💡 Finance Tip"}</Button>
                                            <Button size="sm" variant="outline" className="h-7 text-[11px] border-amber-300 text-amber-700 hover:bg-amber-50" onClick={() => composeWithAI("tip", "customer")} disabled={aiBusy} data-testid="ai-tip-customer">{aiBusy === "tip-customer" ? "..." : "💡 Customer Tip"}</Button>
                                            <Button size="sm" variant="outline" className="h-7 text-[11px] border-amber-300 text-amber-700 hover:bg-amber-50" onClick={() => composeWithAI("tip", "gst")} disabled={aiBusy} data-testid="ai-tip-gst">{aiBusy === "tip-gst" ? "..." : "💡 GST Tip"}</Button>
                                        </span>
                                    </div>
                                    <div className="text-[10px] text-muted-foreground mt-2">
                                        Auto-generates today&apos;s message · powered by Emergent AI · one click to load into message box below
                                    </div>
                                </div>

                                <div>
                                    <Label className="text-xs text-muted-foreground">Quick Templates</Label>
                                    <div className="flex flex-wrap gap-1.5 mt-1.5">
                                        {templates.map((t) => (
                                            <button
                                                key={t.key}
                                                onClick={() => applyTemplate(t)}
                                                className="text-[11px] px-2.5 py-1 rounded-full border border-emerald-500/30 hover:bg-emerald-500/10 hover:border-emerald-500 transition"
                                                data-testid={`tpl-${t.key}`}
                                            >
                                                {t.label}
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                <div>
                                    <Label htmlFor="wa-campaign-name">Campaign Name (history mein dikhega)</Label>
                                    <Input
                                        id="wa-campaign-name"
                                        value={campaignName}
                                        onChange={(e) => setCampaignName(e.target.value)}
                                        placeholder="e.g. Diwali Offer Oct-2026"
                                        data-testid="wa-campaign-name"
                                        className="mt-1"
                                    />
                                </div>

                                <div>
                                    <Label htmlFor="wa-message">Message Body</Label>
                                    <Textarea
                                        id="wa-message"
                                        value={message}
                                        onChange={(e) => setMessage(e.target.value)}
                                        placeholder={"Hello {{name}}, hum REGAL MARKETING se hain. Aapke liye special offer..."}
                                        rows={6}
                                        className="mt-1 font-mono text-sm"
                                        data-testid="wa-message"
                                    />
                                    <div className="text-[10px] text-muted-foreground mt-1">
                                        Variables: <code>{`{{name}}`}</code>, <code>{`{{shop_name}}`}</code>, <code>{`{{customer_name}}`}</code> auto-fill honge. Custom variables niche set karo.
                                    </div>
                                </div>

                                {detectedVars.length > 0 && (
                                    <div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-3">
                                        <Label className="text-xs font-semibold text-amber-700 dark:text-amber-400 mb-2 flex items-center gap-1">
                                            <AlertTriangle className="h-3.5 w-3.5" /> Custom Variables Needed
                                        </Label>
                                        <div className="grid grid-cols-2 gap-2">
                                            {detectedVars.map((v) => (
                                                <div key={v}>
                                                    <Label className="text-[10px]" htmlFor={`var-${v}`}>{v}</Label>
                                                    <Input
                                                        id={`var-${v}`}
                                                        value={extraVars[v] || ""}
                                                        onChange={(e) => setExtraVars({ ...extraVars, [v]: e.target.value })}
                                                        placeholder={`Value for ${v}`}
                                                        className="h-8 text-xs"
                                                        data-testid={`var-${v}`}
                                                    />
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                <div className="rounded-lg bg-emerald-500/5 border border-emerald-500/20 p-3">
                                    <Label className="text-xs text-emerald-700 dark:text-emerald-400 font-semibold mb-1.5 block">📱 Live Preview (first selected contact ke saath)</Label>
                                    <pre className="whitespace-pre-wrap text-sm font-mono">{livePreview || <span className="text-muted-foreground italic">— message likhna shuru karein —</span>}</pre>
                                </div>
                            </CardContent>
                        </Card>

                        {/* Right: Recipients */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="flex items-center gap-2 text-base">
                                    <Users className="h-4 w-4 text-blue-500" /> Recipients
                                    <Badge variant="outline" className="ml-auto" data-testid="wa-selected-count">{selectedCount} selected</Badge>
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                <div className="flex flex-wrap gap-1.5">
                                    {[
                                        { k: "all", label: "All" },
                                        { k: "customers", label: "Customers" },
                                        { k: "vendors", label: "Vendors" },
                                        { k: "due-payment", label: "Due ₹" },
                                        { k: "high-value", label: "High Value" },
                                        { k: "credit-balance", label: "Advance ₹" },
                                    ].map((a) => (
                                        <button
                                            key={a.k}
                                            onClick={() => setAudience(a.k)}
                                            className={`text-[11px] py-1 px-2.5 rounded-full border transition ${audience === a.k ? "bg-emerald-500 text-white border-emerald-500" : "border-border hover:bg-muted"}`}
                                            data-testid={`aud-${a.k}`}
                                            title={a.k === "due-payment" ? "Customers with outstanding > 0" : a.k === "high-value" ? "Outstanding > ₹10,000" : a.k === "credit-balance" ? "You owe these parties" : ""}
                                        >
                                            {a.label}
                                        </button>
                                    ))}
                                </div>
                                <div className="relative">
                                    <Search className="absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
                                    <Input
                                        value={search}
                                        onChange={(e) => setSearch(e.target.value)}
                                        placeholder="Naam, phone se search..."
                                        className="h-8 pl-7 text-xs"
                                        data-testid="wa-search"
                                    />
                                </div>
                                <div className="flex gap-1.5">
                                    <Button size="sm" variant="outline" onClick={selectAllVisible} className="flex-1 h-7 text-[10px]" data-testid="wa-select-all">Select All ({withPhone.length})</Button>
                                    <Button size="sm" variant="outline" onClick={clearSelection} className="h-7 text-[10px]" data-testid="wa-clear">Clear</Button>
                                </div>
                                <div className="max-h-[350px] overflow-y-auto space-y-1 border rounded-md p-1">
                                    {withPhone.length === 0 ? (
                                        <p className="text-center text-xs text-muted-foreground py-4">No contacts with phone numbers</p>
                                    ) : withPhone.map((p) => (
                                        <label
                                            key={p.id}
                                            className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted cursor-pointer text-sm"
                                            data-testid={`party-${p.id}`}
                                        >
                                            <Checkbox
                                                checked={selected.has(p.id)}
                                                onCheckedChange={() => toggle(p.id)}
                                                data-testid={`party-check-${p.id}`}
                                            />
                                            <div className="min-w-0 flex-1">
                                                <div className="truncate font-medium">{p.name}</div>
                                                <div className="text-[10px] text-muted-foreground font-mono flex items-center gap-1">
                                                    <Phone className="h-2.5 w-2.5" /> {p.phone}
                                                </div>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            </CardContent>
                        </Card>
                    </div>

                    <div className="mt-4 flex justify-end">
                        <Button onClick={buildPreview} disabled={selectedCount === 0 || !message.trim()} className="bg-emerald-600 hover:bg-emerald-700 text-white" data-testid="wa-build-preview">
                            <Send className="h-4 w-4 mr-2" /> Preview & Send ({selectedCount})
                        </Button>
                    </div>
                </TabsContent>

                {/* =========== TAB 2: Send =========== */}
                <TabsContent value="send" className="mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2">
                                <Play className="h-5 w-5 text-emerald-600" /> Bulk Send Console
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            {previewItems.length === 0 ? (
                                <div className="text-center py-8">
                                    <MessageCircle className="h-12 w-12 mx-auto text-muted-foreground/30 mb-2" />
                                    <p className="text-sm text-muted-foreground">Compose tab par jaa kar contacts select karo aur "Preview & Send" pe click karo.</p>
                                </div>
                            ) : (
                                <>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                                        <div className="rounded-lg bg-emerald-500/10 border border-emerald-500/20 p-3">
                                            <div className="text-[10px] uppercase tracking-wider text-emerald-700 dark:text-emerald-400">Recipients</div>
                                            <div className="font-display text-2xl font-bold">{previewItems.length}</div>
                                        </div>
                                        <div className="rounded-lg bg-blue-500/10 border border-blue-500/20 p-3">
                                            <div className="text-[10px] uppercase tracking-wider text-blue-700 dark:text-blue-400">Progress</div>
                                            <div className="font-display text-2xl font-bold">{progress.current}/{progress.total || previewItems.length}</div>
                                        </div>
                                        <div className="rounded-lg bg-amber-500/10 border border-amber-500/20 p-3">
                                            <div className="text-[10px] uppercase tracking-wider text-amber-700 dark:text-amber-400">Delay (sec)</div>
                                            <Input
                                                type="number"
                                                value={delayMs / 1000}
                                                onChange={(e) => setDelayMs(Math.max(1, Number(e.target.value)) * 1000)}
                                                className="h-7 text-sm font-bold"
                                                min="1"
                                                max="60"
                                                data-testid="wa-delay"
                                            />
                                        </div>
                                    </div>

                                    <div className="flex flex-wrap gap-2 mb-4">
                                        {!sending ? (
                                            <Button onClick={startBulk} className="bg-emerald-600 hover:bg-emerald-700 text-white" data-testid="wa-start-bulk">
                                                <Play className="h-4 w-4 mr-2" /> Start Bulk Send
                                            </Button>
                                        ) : (
                                            <>
                                                <Button onClick={togglePause} variant="outline" data-testid="wa-pause">
                                                    <Pause className="h-4 w-4 mr-2" /> {pausedRef ? "Resume" : "Pause"}
                                                </Button>
                                                <Button onClick={stopBulk} variant="destructive" data-testid="wa-stop">
                                                    <Square className="h-4 w-4 mr-2" /> Stop
                                                </Button>
                                            </>
                                        )}
                                        <Button variant="outline" onClick={() => setTab("compose")}>
                                            <X className="h-4 w-4 mr-1.5" /> Back to Compose
                                        </Button>
                                    </div>

                                    <div className="rounded-lg border bg-amber-500/5 border-amber-500/30 p-3 mb-3">
                                        <p className="text-xs text-amber-700 dark:text-amber-400">
                                            ⚠️ <strong>Important:</strong> Browser ka popup blocker disable karein (top-right URL bar mein "Allow popups for this site"). Har contact ke liye WhatsApp Web/desktop khulega aur message pre-typed hoga — bas <kbd className="px-1 py-0.5 rounded bg-emerald-600 text-white text-[10px]">Send</kbd> button dabana hai.
                                        </p>
                                    </div>

                                    <div className="max-h-[400px] overflow-y-auto space-y-1 border rounded-md p-2">
                                        {previewItems.map((it, idx) => {
                                            const isDone = idx < progress.current;
                                            const isCurrent = idx === progress.current - 1 && sending;
                                            return (
                                                <div
                                                    key={it.party_id}
                                                    className={`flex items-center justify-between p-2 rounded text-sm border ${
                                                        isDone ? "bg-emerald-500/10 border-emerald-500/30" :
                                                        isCurrent ? "bg-blue-500/10 border-blue-500/30 animate-pulse" :
                                                        "border-border/50"
                                                    }`}
                                                    data-testid={`preview-${it.party_id}`}
                                                >
                                                    <div className="min-w-0 flex-1">
                                                        <div className="font-medium truncate">{it.name}</div>
                                                        <div className="text-[10px] text-muted-foreground font-mono">+{it.phone_digits}</div>
                                                    </div>
                                                    <div className="flex items-center gap-1.5 shrink-0">
                                                        {isDone && <CheckCircle2 className="h-4 w-4 text-emerald-600" />}
                                                        <Button
                                                            size="icon"
                                                            variant="ghost"
                                                            className="h-7 w-7"
                                                            onClick={() => window.open(it.wa_url, "_blank", "noopener,noreferrer")}
                                                            title="Open this chat manually"
                                                            data-testid={`open-${it.party_id}`}
                                                        >
                                                            <ExternalLink className="h-3.5 w-3.5" />
                                                        </Button>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* =========== TAB 3: History =========== */}
                <TabsContent value="history" className="mt-4">
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <CardTitle className="flex items-center gap-2"><HistoryIcon className="h-5 w-5" /> Campaign History</CardTitle>
                            <Button size="sm" variant="ghost" onClick={() => api.get("/marketing/campaigns").then((r) => setHistory(r.data || []))} data-testid="wa-refresh-history">
                                <RefreshCw className="h-4 w-4" />
                            </Button>
                        </CardHeader>
                        <CardContent>
                            {history.length === 0 ? (
                                <p className="text-center text-sm text-muted-foreground py-6">No campaigns yet.</p>
                            ) : (
                                <div className="divide-y">
                                    {history.map((c) => (
                                        <div key={c.id} className="py-3" data-testid={`history-${c.id}`}>
                                            <div className="flex items-start justify-between gap-2">
                                                <div className="min-w-0">
                                                    <div className="font-semibold truncate">{c.name}</div>
                                                    <div className="text-[10px] text-muted-foreground mt-0.5">{new Date(c.created_at).toLocaleString("en-IN")} · {c.channel}</div>
                                                </div>
                                                <Badge variant="outline" className="text-[10px] shrink-0">{c.sent}/{c.recipient_count} sent</Badge>
                                            </div>
                                            <p className="text-xs text-muted-foreground mt-1.5 line-clamp-2 font-mono">{c.message}</p>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    );
}
