"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  Archive,
  Building2,
  Loader2,
  Mail,
  Megaphone,
  RefreshCw,
  Search,
  Send,
  UserCircle,
} from "lucide-react";
import { PageLayout } from "@/components/design-system/page-layout";
import { EmailMessageBody } from "@/components/inbox/email-message-body";
import { AiClassificationPanel } from "@/components/inbox/ai-classification-panel";
import { AiNextBestActionPanel } from "@/components/ai/ai-next-best-action-panel";
import { AiFollowUpPanel } from "@/components/ai/ai-follow-up-panel";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ListPagination } from "@/components/ui/list-pagination";
import { StatusToast } from "@/components/ui/status-toast";
import { useLocale } from "@/components/providers/locale-provider";
import { cn } from "@/lib/utils";
import Link from "next/link";

type ThreadFilter =
  | "all"
  | "unread"
  | "new"
  | "classified"
  | "lead_worthy"
  | "linked_lead"
  | "campaign"
  | "sequence"
  | "archived";

type ThreadRow = {
  _id: string;
  subject?: string;
  lastSnippet?: string;
  lastFromEmail?: string;
  lastMessageAt: string;
  lastDirection?: "inbound" | "outbound";
  unreadCount: number;
  status: string;
  lastIntent?: string;
  hasAiClassification?: boolean;
  companyId?: { nameAr?: string; nameEn?: string; _id?: string };
  personId?: { fullName?: string; _id?: string };
  campaignId?: { name?: string; _id?: string };
  sequenceId?: { name?: string; _id?: string };
  leadId?: { _id?: string; status?: string };
  mailboxId?: string;
  mailboxEmail?: string;
  mailboxName?: string;
};

type MailboxOption = {
  _id: string;
  name: string;
  email: string;
  isDefault: boolean;
  hasImapConfig?: boolean;
  lastSyncAt?: string | null;
};

type MailboxSelection = "all" | string;

type MailboxContext = {
  defaultMailboxId?: string | null;
  activeMailboxCount?: number;
  selectedMailbox?: string | null;
  lastSyncAt?: string | null;
  unthreadedReplyCount?: number;
  totalThreads?: number;
};

type ThreadMessage = {
  _id: string;
  direction?: "inbound" | "outbound";
  fromEmail: string;
  toEmail?: string;
  subject?: string;
  receivedAt: string;
  status: string;
  bodyText?: string;
  bodyHtml?: string;
  linkedEmailMessage?: {
    sentAt?: string;
    openedAt?: string;
    clickedAt?: string;
    status?: string;
    trackingId?: string;
  };
};

type ThreadDetail = {
  thread: ThreadRow & {
    companyId?: Record<string, unknown>;
    personId?: Record<string, unknown>;
    campaignId?: Record<string, unknown>;
    sequenceId?: Record<string, unknown>;
    leadId?: Record<string, unknown>;
  };
  messages: ThreadMessage[];
  classification?: Record<string, unknown> | null;
  lead?: { _id?: string; status?: string; temperature?: string } | null;
  opportunity?: { _id?: string; stage?: string } | null;
  sequenceRecipient?: {
    status?: string;
    stopReason?: string;
    currentStepNumber?: number;
    nextSendAt?: string | null;
  } | null;
};

const FILTER_OPTIONS: Array<{ id: ThreadFilter; ar: string; en: string }> = [
  { id: "all", ar: "الكل", en: "All" },
  { id: "unread", ar: "غير مقروء", en: "Unread" },
  { id: "new", ar: "جديد", en: "New" },
  { id: "classified", ar: "مُصنَّف", en: "Classified" },
  { id: "lead_worthy", ar: "يستحق Lead", en: "Lead-worthy" },
  { id: "linked_lead", ar: "مرتبط بـ Lead", en: "Linked Lead" },
  { id: "campaign", ar: "ردود الحملات", en: "Campaign" },
  { id: "sequence", ar: "ردود السلاسل", en: "Sequence" },
  { id: "archived", ar: "مؤرشف", en: "Archived" },
];

const PAGE_SIZES = [25, 50, 100];

export function InboxConversationCenter({
  initialThreadId,
}: {
  initialThreadId?: string;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const router = useRouter();
  const searchParams = useSearchParams();

  const [threads, setThreads] = useState<ThreadRow[]>([]);
  const [selectedId, setSelectedId] = useState<string | undefined>(initialThreadId);
  const [detail, setDetail] = useState<ThreadDetail | null>(null);
  const [filter, setFilter] = useState<ThreadFilter>("all");
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(25);
  const [totalPages, setTotalPages] = useState(1);
  const [listLoading, setListLoading] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [sending, setSending] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [backfilling, setBackfilling] = useState(false);
  const [toast, setToast] = useState<{ message: string; variant: "success" | "error" } | null>(
    null
  );
  const [mailboxes, setMailboxes] = useState<MailboxOption[]>([]);
  const [mailboxesReady, setMailboxesReady] = useState(false);
  const [mailboxSelection, setMailboxSelection] = useState<MailboxSelection | null>(null);
  const [mailboxBanner, setMailboxBanner] = useState<string | null>(null);
  const [mailboxContext, setMailboxContext] = useState<MailboxContext | null>(null);

  const selectedRef = useRef<string | undefined>(initialThreadId);
  const mailboxRef = useRef<MailboxSelection | "">("");
  const mailboxUrlSyncedRef = useRef(false);

  const showToast = useCallback((message: string, variant: "success" | "error") => {
    setToast({ message, variant });
    window.setTimeout(() => setToast(null), 4000);
  }, []);

  const updateMailboxUrl = useCallback(
    (selection: MailboxSelection, threadId?: string) => {
      const params = new URLSearchParams(searchParams.toString());
      params.delete("mailbox");
      params.delete("mailboxId");
      if (selection === "all") {
        params.set("mailbox", "all");
      } else if (selection) {
        params.set("mailboxId", selection);
      }
      if (threadId) params.set("thread", threadId);
      else params.delete("thread");
      const qs = params.toString();
      router.replace(qs ? `/inbox?${qs}` : "/inbox", { scroll: false });
    },
    [router, searchParams]
  );

  const loadMailboxes = useCallback(async () => {
    try {
      const res = await fetch("/api/email/mailboxes");
      const json = (await res.json()) as { data?: MailboxOption[]; error?: string };
      if (!res.ok) {
        setMailboxes([]);
        setMailboxBanner(json.error ?? (isAr ? "تعذّر تحميل صناديق البريد" : "Could not load mailboxes"));
        return;
      }
      const list = json.data ?? [];
      setMailboxes(list);
      if (list.length === 0) {
        setMailboxSelection(null);
        setMailboxBanner(
          isAr
            ? "لا توجد صناديق بريد نشطة. أضف صندوق بريد من الإعدادات."
            : "No active mailboxes. Add one in Settings."
        );
        return;
      }

      const urlMailbox = searchParams.get("mailbox");
      const urlMailboxId = searchParams.get("mailboxId");
      let nextSelection: MailboxSelection;
      if (urlMailbox === "all") {
        nextSelection = "all";
      } else if (urlMailboxId && list.some((m) => m._id === urlMailboxId)) {
        nextSelection = urlMailboxId;
      } else {
        const defaultBox = list.find((m) => m.isDefault) ?? list[0];
        nextSelection = defaultBox._id;
        if (!urlMailbox && !urlMailboxId && !mailboxUrlSyncedRef.current) {
          mailboxUrlSyncedRef.current = true;
          const params = new URLSearchParams(searchParams.toString());
          params.set("mailboxId", nextSelection);
          if (initialThreadId) params.set("thread", initialThreadId);
          router.replace(`/inbox?${params.toString()}`, { scroll: false });
        }
      }

      setMailboxSelection(nextSelection);
      mailboxRef.current = nextSelection;

      const selected = list.find((m) => m._id === nextSelection);
      if (selected && selected.hasImapConfig === false) {
        setMailboxBanner(
          isAr ? "إعدادات IMAP غير مكتملة لهذا الصندوق." : "IMAP settings are incomplete for this mailbox."
        );
      } else {
        setMailboxBanner(null);
      }
    } catch {
      setMailboxBanner(isAr ? "تعذّر تحميل صناديق البريد" : "Could not load mailboxes");
    } finally {
      setMailboxesReady(true);
    }
  }, [isAr, initialThreadId, router, searchParams]);

  const loadThreads = useCallback(async () => {
    if (!mailboxesReady) return;
    if (mailboxes.length === 0) {
      setThreads([]);
      setTotalPages(1);
      return;
    }

    setListLoading(true);
    try {
      const params = new URLSearchParams({
        filter,
        page: String(page),
        limit: String(limit),
      });
      if (q.trim()) params.set("q", q.trim());
      const selection = mailboxRef.current || mailboxSelection || "";
      if (selection === "all") {
        params.set("mailbox", "all");
      } else if (selection) {
        params.set("mailboxId", selection);
      }
      const res = await fetch(`/api/inbox/threads?${params}`);
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Failed");
      setThreads(json.data ?? []);
      setTotalPages(json.pagination?.totalPages ?? 1);
      setMailboxContext(json.mailboxContext ?? null);
    } catch (error) {
      showToast(error instanceof Error ? error.message : "فشل التحميل", "error");
    } finally {
      setListLoading(false);
    }
  }, [filter, page, limit, q, showToast, mailboxesReady, mailboxes.length, mailboxSelection]);

  const loadDetail = useCallback(
    async (threadId: string, options?: { silent?: boolean }) => {
      if (!options?.silent) setDetailLoading(true);
      try {
        const res = await fetch(`/api/inbox/threads/${threadId}?markRead=true`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error ?? "Failed");
        if (selectedRef.current === threadId) {
          setDetail(json.data as ThreadDetail);
        }
        void loadThreads();
      } catch (error) {
        if (!options?.silent) {
          showToast(error instanceof Error ? error.message : "فشل تحميل المحادثة", "error");
        }
      } finally {
        if (!options?.silent) setDetailLoading(false);
      }
    },
    [loadThreads, showToast]
  );

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void loadMailboxes();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [loadMailboxes]);

  useEffect(() => {
    if (!initialThreadId) return;
    const timeout = window.setTimeout(() => setSelectedId(initialThreadId), 0);
    return () => window.clearTimeout(timeout);
  }, [initialThreadId]);

  useEffect(() => {
    selectedRef.current = selectedId;
  }, [selectedId]);

  useEffect(() => {
    mailboxRef.current = mailboxSelection ?? "";
  }, [mailboxSelection]);

  function handleMailboxChange(value: string) {
    const next: MailboxSelection = value === "all" ? "all" : value;
    setMailboxSelection(next);
    mailboxRef.current = next;
    setPage(1);

    const selected = mailboxes.find((m) => m._id === next);
    if (selected && selected.hasImapConfig === false) {
      setMailboxBanner(
        isAr ? "إعدادات IMAP غير مكتملة لهذا الصندوق." : "IMAP settings are incomplete for this mailbox."
      );
    } else if (mailboxes.length > 0) {
      setMailboxBanner(null);
    }

    updateMailboxUrl(next, selectedId);
  }

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void loadThreads();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [loadThreads]);

  useEffect(() => {
    if (!selectedId) {
      const timeout = window.setTimeout(() => setDetail(null), 0);
      return () => window.clearTimeout(timeout);
    }
    const timeout = window.setTimeout(() => {
      void loadDetail(selectedId);
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [selectedId, loadDetail]);

  useEffect(() => {
    const interval = window.setInterval(() => {
      void loadThreads();
      if (selectedRef.current) {
        void loadDetail(selectedRef.current, { silent: true });
      }
    }, 45000);
    return () => window.clearInterval(interval);
  }, [loadThreads, loadDetail]);

  async function runSync(options?: { all?: boolean }) {
    if (mailboxes.length === 0) {
      showToast(
        isAr
          ? "لا توجد صناديق بريد نشطة. أضف صندوق بريد من الإعدادات."
          : "No active mailboxes. Add one in Settings.",
        "error"
      );
      return;
    }

    const selection = options?.all ? "all" : mailboxRef.current;
    if (selection !== "all") {
      const selected = mailboxes.find((m) => m._id === selection);
      if (selected?.hasImapConfig === false) {
        showToast(
          isAr ? "إعدادات IMAP غير مكتملة لهذا الصندوق." : "IMAP settings are incomplete for this mailbox.",
          "error"
        );
        return;
      }
    }

    setSyncing(true);
    try {
      const body =
        selection === "all" || options?.all
          ? { all: true }
          : { mailboxId: selection };
      const res = await fetch("/api/inbox/sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Sync failed");
      const created =
        typeof json.created === "number"
          ? json.created
          : (json.results as Array<{ created?: number }> | undefined)?.reduce(
              (sum, r) => sum + (r.created ?? 0),
              0
            ) ?? 0;
      showToast(
        isAr ? `تمت المزامنة: ${created} جديد` : `Synced: ${created} new`,
        "success"
      );
      await loadThreads();
      if (selectedId) void loadDetail(selectedId, { silent: true });
    } catch (error) {
      showToast(error instanceof Error ? error.message : "فشل المزامنة", "error");
    } finally {
      setSyncing(false);
    }
  }

  async function backfillThreads() {
    setBackfilling(true);
    try {
      const res = await fetch("/api/admin/maintenance/backfill-inbox-threads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ limit: 1000 }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Backfill failed");
      showToast(
        isAr
          ? `تم ربط ${json.attached ?? 0} رد بالمحادثات`
          : `Linked ${json.attached ?? 0} replies to threads`,
        "success"
      );
      await loadThreads();
    } catch (error) {
      showToast(error instanceof Error ? error.message : "فشل الإصلاح", "error");
    } finally {
      setBackfilling(false);
    }
  }

  async function syncInbox() {
    await runSync();
  }

  async function threadAction(path: string, body?: Record<string, unknown>) {
    if (!selectedId) return;
    const res = await fetch(`/api/inbox/threads/${selectedId}/${path}`, {
      method: "POST",
      headers: body ? { "Content-Type": "application/json" } : undefined,
      body: body ? JSON.stringify(body) : undefined,
    });
    const json = await res.json();
    if (!res.ok) throw new Error(json.error ?? "Failed");
    return json;
  }

  async function sendReply() {
    if (!selectedId || !replyText.trim()) return;
    setSending(true);
    try {
      await threadAction("reply", { text: replyText.trim() });
      setReplyText("");
      showToast(isAr ? "تم إرسال الرد" : "Reply sent", "success");
      void loadDetail(selectedId);
      void loadThreads();
    } catch (error) {
      showToast(error instanceof Error ? error.message : "فشل الإرسال", "error");
    } finally {
      setSending(false);
    }
  }

  const selectedMailboxLabel =
    mailboxSelection === "all"
      ? isAr
        ? "كل الصناديق"
        : "All mailboxes"
      : mailboxes.find((m) => m._id === mailboxSelection)?.name ??
        mailboxes.find((m) => m._id === mailboxSelection)?.email ??
        "—";

  const lastSyncLabel = mailboxContext?.lastSyncAt
    ? new Date(mailboxContext.lastSyncAt).toLocaleString(isAr ? "ar-SA" : "en-US")
    : isAr
      ? "لم تتم بعد"
      : "Never";

  const latestInboundReplyId = detail
    ? [...detail.messages].reverse().find((m) => m.direction !== "outbound")?._id ?? ""
    : "";

  const sequenceActive =
    detail?.sequenceRecipient?.status != null &&
    detail.sequenceRecipient.status !== "stopped";

  const company = detail?.thread.companyId as
    | { nameAr?: string; nameEn?: string; sector?: string; city?: string; website?: string; leadScore?: number; _id?: string }
    | undefined;
  const person = detail?.thread.personId as
    | { fullName?: string; jobTitle?: string; email?: string; mobile?: string; isDecisionMaker?: boolean; _id?: string }
    | undefined;

  return (
    <>
      <StatusToast
        message={toast?.message ?? null}
        variant={toast?.variant}
        onDismiss={() => setToast(null)}
      />
      <PageLayout
        title={isAr ? "صندوق الوارد" : "Inbox"}
        description={
          isAr
            ? "مركز المحادثات — الحملات والسلاسل والـ Leads"
            : "Conversation center — campaigns, sequences & leads"
        }
        maxWidth={false}
        actions={
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={syncing}
            onClick={() => void syncInbox()}
          >
            {syncing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
            {isAr ? "مزامنة" : "Sync"}
          </Button>
        }
      >
        {mailboxBanner ? (
          <p className="mb-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
            {mailboxBanner}
          </p>
        ) : null}

        <div className="mb-4 flex flex-wrap items-center gap-2">
          <label className="flex flex-col gap-1 text-sm">
            <span className="text-muted-foreground">
              {isAr ? "صندوق البريد" : "Mailbox"}
            </span>
            <select
              className="h-9 min-w-[220px] rounded-md border border-border bg-background px-2 text-sm"
              value={mailboxSelection ?? ""}
              disabled={!mailboxesReady || mailboxes.length === 0}
              onChange={(e) => handleMailboxChange(e.target.value)}
            >
              <option value="all">{isAr ? "كل الصناديق" : "All Mailboxes"}</option>
              {mailboxes.map((m) => (
                <option key={m._id} value={m._id}>
                  {m.isDefault
                    ? `${m.name} (${m.email})${isAr ? " — افتراضي" : " — default"}`
                    : `${m.name} (${m.email})`}
                </option>
              ))}
            </select>
          </label>
          <div className="relative min-w-[200px] flex-1">
            <Search className="absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              className="ps-9"
              placeholder={isAr ? "بحث في المحادثات..." : "Search conversations..."}
              value={q}
              onChange={(e) => {
                setQ(e.target.value);
                setPage(1);
              }}
            />
          </div>
          <select
            className="h-9 rounded-md border border-border bg-background px-2 text-sm"
            value={limit}
            onChange={(e) => {
              setLimit(Number(e.target.value));
              setPage(1);
            }}
          >
            {PAGE_SIZES.map((size) => (
              <option key={size} value={size}>
                {size}
              </option>
            ))}
          </select>
        </div>

        <div className="mb-3 flex flex-wrap gap-1">
          {FILTER_OPTIONS.map((opt) => (
            <Button
              key={opt.id}
              type="button"
              size="sm"
              variant={filter === opt.id ? "default" : "outline"}
              onClick={() => {
                setFilter(opt.id);
                setPage(1);
              }}
            >
              {isAr ? opt.ar : opt.en}
            </Button>
          ))}
        </div>

        <div className="grid min-h-[70vh] gap-0 overflow-hidden rounded-xl border border-border lg:grid-cols-12">
          {/* Thread list */}
          <aside className="border-b border-border lg:col-span-3 lg:border-b-0 lg:border-e">
            <div className="max-h-[70vh] overflow-y-auto">
              {listLoading && threads.length === 0 ? (
                <p className="p-4 text-sm text-muted-foreground">
                  {isAr ? "جاري التحميل..." : "Loading..."}
                </p>
              ) : null}
              {threads.map((thread) => {
                const active = thread._id === selectedId;
                const companyName =
                  thread.companyId?.nameAr ?? thread.companyId?.nameEn;
                const showMailboxBadge = mailboxSelection === "all";
                const mailboxLabel =
                  thread.mailboxName ?? thread.mailboxEmail ?? "";
                return (
                  <button
                    key={thread._id}
                    type="button"
                    onClick={() => setSelectedId(thread._id)}
                    className={cn(
                      "w-full border-b border-border/50 px-3 py-3 text-start transition-colors hover:bg-muted/40",
                      active && "bg-primary/5 border-s-2 border-s-primary",
                      thread.unreadCount > 0 && !active && "bg-muted/20"
                    )}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <span
                        className={cn(
                          "truncate text-sm font-medium",
                          thread.unreadCount > 0 && "font-bold"
                        )}
                        dir="ltr"
                      >
                        {thread.lastFromEmail ?? "—"}
                      </span>
                      <span className="shrink-0 text-[10px] text-muted-foreground">
                        {new Date(thread.lastMessageAt).toLocaleDateString(
                          isAr ? "ar-SA" : "en-US"
                        )}
                      </span>
                    </div>
                    {companyName ? (
                      <p className="mt-0.5 truncate text-xs text-muted-foreground">
                        {companyName}
                      </p>
                    ) : null}
                    <p className="mt-1 truncate text-sm">
                      {thread.subject ?? (isAr ? "(بدون موضوع)" : "(No subject)")}
                    </p>
                    <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
                      {thread.lastSnippet}
                    </p>
                    <div className="mt-2 flex flex-wrap gap-1">
                      {showMailboxBadge && mailboxLabel ? (
                        <Badge variant="secondary" className="text-[10px]">
                          {mailboxLabel}
                        </Badge>
                      ) : null}
                      {thread.unreadCount > 0 ? (
                        <Badge variant="default" className="text-[10px]">
                          {thread.unreadCount}
                        </Badge>
                      ) : null}
                      {thread.lastIntent ? (
                        <Badge variant="secondary" className="text-[10px]">
                          {thread.lastIntent}
                        </Badge>
                      ) : null}
                      {thread.campaignId?.name ? (
                        <Badge variant="secondary" className="text-[10px]">
                          {thread.campaignId.name}
                        </Badge>
                      ) : null}
                      {thread.sequenceId?.name ? (
                        <Badge variant="secondary" className="text-[10px]">
                          {thread.sequenceId.name}
                        </Badge>
                      ) : null}
                      {thread.leadId ? (
                        <Badge variant="secondary" className="text-[10px]">
                          Lead
                        </Badge>
                      ) : null}
                    </div>
                  </button>
                );
              })}
              {threads.length === 0 && !listLoading ? (
                <div className="space-y-3 p-4 text-sm">
                  <p className="text-muted-foreground">
                    {isAr ? "لا توجد محادثات لهذا الفلتر." : "No conversations for this filter."}
                  </p>
                  <dl className="space-y-1 text-xs text-muted-foreground">
                    <div>
                      <dt className="inline font-medium">
                        {isAr ? "الصندوق المحدد: " : "Selected mailbox: "}
                      </dt>
                      <dd className="inline">{selectedMailboxLabel}</dd>
                    </div>
                    <div>
                      <dt className="inline font-medium">
                        {isAr ? "صناديق نشطة: " : "Active mailboxes: "}
                      </dt>
                      <dd className="inline">
                        {mailboxContext?.activeMailboxCount ?? mailboxes.length}
                      </dd>
                    </div>
                    <div>
                      <dt className="inline font-medium">
                        {isAr ? "آخر مزامنة: " : "Last sync: "}
                      </dt>
                      <dd className="inline">{lastSyncLabel}</dd>
                    </div>
                    {(mailboxContext?.unthreadedReplyCount ?? 0) > 0 ? (
                      <div>
                        <dt className="inline font-medium">
                          {isAr ? "ردود بدون محادثة: " : "Unthreaded replies: "}
                        </dt>
                        <dd className="inline">{mailboxContext?.unthreadedReplyCount}</dd>
                      </div>
                    ) : null}
                  </dl>
                  <div className="flex flex-col gap-2 pt-1">
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      disabled={syncing}
                      onClick={() => void runSync()}
                    >
                      {syncing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
                      {isAr ? "مزامنة الصندوق المحدد" : "Sync selected mailbox"}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      disabled={syncing}
                      onClick={() => void runSync({ all: true })}
                    >
                      {isAr ? "مزامنة كل الصناديق" : "Sync all mailboxes"}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      disabled={backfilling}
                      onClick={() => void backfillThreads()}
                    >
                      {backfilling ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : null}
                      {isAr ? "إصلاح ربط المحادثات بالصناديق" : "Backfill thread mailbox links"}
                    </Button>
                  </div>
                </div>
              ) : null}
            </div>
            <ListPagination page={page} totalPages={totalPages} onPageChange={setPage} />
          </aside>

          {/* Conversation */}
          <main className="border-b border-border lg:col-span-5 lg:border-b-0 lg:border-e">
            {!selectedId ? (
              <div className="flex h-full min-h-[300px] items-center justify-center text-muted-foreground">
                {isAr ? "اختر محادثة" : "Select a conversation"}
              </div>
            ) : detailLoading && !detail ? (
              <div className="flex h-full items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : detail ? (
              <div className="flex max-h-[70vh] flex-col">
                <header className="border-b border-border px-4 py-3">
                  <h2 className="font-semibold">
                    {detail.thread.subject ?? (isAr ? "(بدون موضوع)" : "(No subject)")}
                  </h2>
                  <div className="mt-2 flex flex-wrap gap-2">
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={() => void threadAction("archive").then(() => loadThreads())}
                    >
                      <Archive className="h-3.5 w-3.5" />
                      {isAr ? "أرشفة" : "Archive"}
                    </Button>
                  </div>
                </header>

                <div className="flex-1 space-y-4 overflow-y-auto p-4">
                  {detail.messages.map((msg) => {
                    const outbound = msg.direction === "outbound";
                    const tracking = msg.linkedEmailMessage;
                    return (
                      <div
                        key={msg._id}
                        className={cn(
                          "flex",
                          outbound ? "justify-end" : "justify-start"
                        )}
                      >
                        <div
                          className={cn(
                            "max-w-[92%] rounded-2xl border px-3 py-2 sm:max-w-[85%]",
                            outbound
                              ? "border-primary/30 bg-primary/5"
                              : "border-border bg-card"
                          )}
                        >
                          <div className="mb-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                            <Badge variant="secondary">
                              {outbound
                                ? isAr
                                  ? "صادر"
                                  : "Sent"
                                : isAr
                                  ? "وارد"
                                  : "Received"}
                            </Badge>
                            <span dir="ltr">{msg.fromEmail}</span>
                            <span>
                              {new Date(msg.receivedAt).toLocaleString(
                                isAr ? "ar-SA" : "en-US"
                              )}
                            </span>
                          </div>
                          <EmailMessageBody bodyHtml={msg.bodyHtml} bodyText={msg.bodyText} />
                          {tracking ? (
                            <div className="mt-2 space-y-1 border-t border-border/50 pt-2 text-[11px] text-muted-foreground">
                              {tracking.sentAt ? (
                                <p>
                                  {isAr ? "أُرسل:" : "Sent:"}{" "}
                                  {new Date(tracking.sentAt).toLocaleString()}
                                </p>
                              ) : null}
                              {tracking.openedAt ? (
                                <p>
                                  {isAr ? "فُتح:" : "Opened:"}{" "}
                                  {new Date(tracking.openedAt).toLocaleString()}
                                </p>
                              ) : null}
                              {tracking.clickedAt ? (
                                <p>
                                  {isAr ? "نُقر:" : "Clicked:"}{" "}
                                  {new Date(tracking.clickedAt).toLocaleString()}
                                </p>
                              ) : null}
                            </div>
                          ) : null}
                        </div>
                      </div>
                    );
                  })}
                </div>

                <footer className="border-t border-border p-3">
                  <textarea
                    className="min-h-[80px] w-full rounded-lg border border-border bg-background p-2 text-sm"
                    dir="auto"
                    placeholder={isAr ? "اكتب ردك..." : "Write your reply..."}
                    value={replyText}
                    onChange={(e) => setReplyText(e.target.value)}
                  />
                  <div className="mt-2 flex justify-end">
                    <Button
                      type="button"
                      size="sm"
                      disabled={sending || !replyText.trim()}
                      onClick={() => void sendReply()}
                    >
                      {sending ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Send className="h-4 w-4" />
                      )}
                      {isAr ? "إرسال" : "Send"}
                    </Button>
                  </div>
                </footer>
              </div>
            ) : null}
          </main>

          {/* CRM + AI panel */}
          <aside className="max-h-[70vh] overflow-y-auto p-4 lg:col-span-4">
            {!selectedId ? (
              <div className="flex h-full min-h-[200px] items-center justify-center text-sm text-muted-foreground">
                <Mail className="me-2 h-4 w-4" />
                {isAr ? "اختر محادثة لعرض السياق والذكاء الاصطناعي" : "Select a conversation for CRM & AI context"}
              </div>
            ) : detailLoading && !detail ? (
              <div className="flex h-full min-h-[200px] items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : detail ? (
              <div className="space-y-4">
                {company ? (
                  <section className="rounded-lg border border-border p-3">
                    <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold">
                      <Building2 className="h-4 w-4" />
                      {isAr ? "الشركة" : "Company"}
                    </h3>
                    <p className="font-medium">{company.nameAr ?? company.nameEn}</p>
                    <dl className="mt-2 space-y-1 text-xs text-muted-foreground">
                      {company.sector ? <div>{company.sector}</div> : null}
                      {company.city ? <div>{company.city}</div> : null}
                      {company.website ? (
                        <div dir="ltr">{company.website}</div>
                      ) : null}
                      {typeof company.leadScore === "number" ? (
                        <div>
                          {isAr ? "درجة Lead:" : "Lead score:"} {company.leadScore}
                        </div>
                      ) : null}
                    </dl>
                    {company._id ? (
                      <Link
                        href={`/market/companies/${company._id}`}
                        className="mt-2 inline-block text-xs text-primary hover:underline"
                      >
                        {isAr ? "فتح الملف" : "View profile"}
                      </Link>
                    ) : null}
                  </section>
                ) : null}

                {person ? (
                  <section className="rounded-lg border border-border p-3">
                    <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold">
                      <UserCircle className="h-4 w-4" />
                      {isAr ? "الشخص" : "Person"}
                    </h3>
                    <p className="font-medium">{person.fullName}</p>
                    <dl className="mt-2 space-y-1 text-xs text-muted-foreground">
                      {person.jobTitle ? <div>{person.jobTitle}</div> : null}
                      {person.email ? <div dir="ltr">{person.email}</div> : null}
                      {person.mobile ? <div dir="ltr">{person.mobile}</div> : null}
                      {person.isDecisionMaker ? (
                        <Badge variant="secondary" className="text-[10px]">
                          {isAr ? "صانع قرار" : "Decision maker"}
                        </Badge>
                      ) : null}
                    </dl>
                    {person._id ? (
                      <Link
                        href={`/market/people/${person._id}`}
                        className="mt-2 inline-block text-xs text-primary hover:underline"
                      >
                        {isAr ? "فتح الملف" : "View profile"}
                      </Link>
                    ) : null}
                  </section>
                ) : null}

                {detail.lead ? (
                  <section className="rounded-lg border border-border p-3">
                    <h3 className="text-sm font-semibold">{isAr ? "Lead" : "Lead"}</h3>
                    <p className="text-sm">{detail.lead.status}</p>
                    {detail.lead.temperature ? (
                      <Badge variant="secondary">{detail.lead.temperature}</Badge>
                    ) : null}
                    {detail.opportunity?.stage ? (
                      <p className="mt-1 text-xs text-muted-foreground">
                        {detail.opportunity.stage}
                      </p>
                    ) : null}
                    {detail.lead._id ? (
                      <Link
                        href={`/leads/${detail.lead._id}`}
                        className="mt-2 inline-block text-xs text-primary hover:underline"
                      >
                        {isAr ? "فتح Lead" : "Open lead"}
                      </Link>
                    ) : null}
                  </section>
                ) : null}

                {(detail.thread.campaignId as { name?: string })?.name ? (
                  <section className="rounded-lg border border-border p-3">
                    <h3 className="flex items-center gap-2 text-sm font-semibold">
                      <Megaphone className="h-4 w-4" />
                      {isAr ? "الحملة" : "Campaign"}
                    </h3>
                    <p>{(detail.thread.campaignId as { name?: string }).name}</p>
                  </section>
                ) : null}

                {detail.sequenceRecipient ? (
                  <section className="rounded-lg border border-border p-3">
                    <h3 className="text-sm font-semibold">
                      {isAr ? "السلسلة" : "Sequence"}
                    </h3>
                    <p className="text-sm">
                      {(detail.thread.sequenceId as { name?: string })?.name}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {detail.sequenceRecipient.status}
                      {detail.sequenceRecipient.stopReason
                        ? ` — ${detail.sequenceRecipient.stopReason}`
                        : ""}
                    </p>
                    {detail.sequenceRecipient.status !== "stopped" ? (
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        className="mt-2"
                        onClick={() =>
                          void threadAction("stop-sequence").then(() =>
                            loadDetail(selectedId!)
                          )
                        }
                      >
                        {isAr ? "إيقاف السلسلة" : "Stop sequence"}
                      </Button>
                    ) : null}
                  </section>
                ) : null}

                {selectedId ? (
                  <AiNextBestActionPanel entityType="thread" entityId={selectedId} />
                ) : null}

                {selectedId && detail ? (
                  <AiFollowUpPanel
                    lastReply={detail.messages.filter((m) => m.direction !== "outbound").at(-1)?.bodyText}
                    conversationHistory={detail.messages
                      .map((m) => `${m.fromEmail}: ${m.bodyText ?? m.subject ?? ""}`)
                      .join("\n")}
                    companyContext={company?.nameAr ?? company?.nameEn}
                    leadContext={detail.lead?.status}
                    subject={detail.thread.subject}
                    onApply={(html) => {
                      const text = html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
                      setReplyText(text);
                    }}
                  />
                ) : null}

                <AiClassificationPanel
                  emailReplyId={latestInboundReplyId}
                  threadId={selectedId}
                  sequenceActive={sequenceActive}
                  classification={
                    (detail.classification as Parameters<
                      typeof AiClassificationPanel
                    >[0]["classification"]) ?? null
                  }
                  onRefresh={() => {
                    if (selectedId) void loadDetail(selectedId, { silent: true });
                  }}
                />
              </div>
            ) : (
              <div className="flex h-full min-h-[200px] items-center justify-center text-sm text-muted-foreground">
                {isAr ? "تعذّر تحميل المحادثة" : "Could not load conversation"}
              </div>
            )}
          </aside>
        </div>
      </PageLayout>
    </>
  );
}
