"use client";

import { useState, useCallback, useEffect } from "react";
import {
  Phone,
  PhoneCall,
  Settings,
  BarChart3,
  Clock,
  CheckCircle,
  AlertCircle,
  RefreshCw,
  Search,
  Activity,
  Loader2,
  Lock,
  ArrowRight,
  Calendar,
  X,
  User,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import VoiceAgentSetupWizard from "./voice-agent/VoiceAgentSetupWizard";
import PhoneConfigPanel from "./voice-agent/PhoneConfigPanel";
import StructuredPromptEditor from "./voice-agent/StructuredPromptEditor";
import ConversationSettingsPanel from "./voice-agent/ConversationSettingsPanel";
import {
  useVoiceAgentData,
  type RecentCall,
  type VoiceAgentStats,
} from "./voice-agent/useVoiceAgentData";
import type {
  VoiceAgentConfig,
  PromptSections,
  ConversationSettings,
  VoiceSettings,
} from "@/lib/types/voice-agent.types";

// ── Sub-tab types ────────────────────────────────────────────────────

type SubTab = "overview" | "calls" | "settings" | "phone" | "analytics";

interface SubTabConfig {
  id: SubTab;
  labelEn: string;
  labelAr: string;
  icon: React.ReactNode;
}

// ── Conversation/analytics types ─────────────────────────────────────

interface ConversationItem {
  id: string;
  callId: string;
  customerPhone?: string;
  customerName?: string;
  startTime: string;
  endTime?: string;
  durationSeconds: number;
  status: "started" | "ended" | "failed";
  transcript: Array<{
    speaker: "agent" | "user";
    text: string;
    timestamp: string;
  }>;
  sentiment?: string;
  bookingCreated?: boolean;
  callOutcome?: string;
}

interface ConversationsPagination {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface AnalyticsData {
  totalCalls: number;
  avgDurationSeconds: number;
  successRate: number;
  appointmentsBooked: number;
  missedCalls: number;
  escalatedCalls: number;
}

interface PhoneConfigData {
  connectionType: string;
  phoneNumber?: string;
  isActive: boolean;
  elevenlabsPhoneId?: string;
}

// ── Props ────────────────────────────────────────────────────────────

interface VoiceAgentPanelProps {
  lang: Lang;
  hasAccess?: boolean;
}

// ── Main Component ───────────────────────────────────────────────────

export default function VoiceAgentPanel({
  lang,
  hasAccess,
}: VoiceAgentPanelProps) {
  const isAr = lang === "ar";
  const {
    isProvisioned,
    isLoading,
    error,
    agent,
    stats,
    recentCalls,
    refresh,
  } = useVoiceAgentData();

  // ── Access Gate ──────────────────────────────────────────────────
  if (hasAccess === false) {
    return <UpgradePrompt isAr={isAr} />;
  }

  // ── Loading State ────────────────────────────────────────────────
  if (isLoading) {
    return <SkeletonLoader isAr={isAr} />;
  }

  // ── Error State ──────────────────────────────────────────────────
  if (error) {
    return (
      <div className="space-y-8">
        <PanelHeader isAr={isAr} onRefresh={refresh} refreshing={false} />
        <div className="bg-white rounded-2xl border border-red-200 p-8 text-center">
          <AlertCircle className="mx-auto h-10 w-10 text-red-400 mb-3" />
          <p className="text-red-600 font-medium">
            {isAr
              ? "حدث خطأ أثناء تحميل البيانات"
              : "Failed to load voice agent data"}
          </p>
          <p className="text-sm text-slate-500 mt-1">{error}</p>
          <button
            onClick={refresh}
            className="mt-4 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 transition-colors"
          >
            {isAr ? "إعادة المحاولة" : "Retry"}
          </button>
        </div>
      </div>
    );
  }

  // ── Setup Wizard ─────────────────────────────────────────────────
  if (!isProvisioned) {
    return (
      <div className="space-y-8">
        <PanelHeader isAr={isAr} onRefresh={refresh} refreshing={false} />
        <VoiceAgentSetupWizard lang={lang} onComplete={refresh} />
      </div>
    );
  }

  // ── Full Dashboard ───────────────────────────────────────────────
  return (
    <ProvisionedDashboard
      isAr={isAr}
      agent={agent}
      stats={stats}
      recentCalls={recentCalls}
      onRefresh={refresh}
    />
  );
}

// ── Panel Header ─────────────────────────────────────────────────────

function PanelHeader({
  isAr,
  onRefresh,
  refreshing,
}: {
  isAr: boolean;
  onRefresh: () => void;
  refreshing: boolean;
}) {
  return (
    <div className="flex items-center justify-between">
      <div>
        <h2 className="text-2xl font-bold text-slate-900">
          {isAr ? "الوكيل الصوتي" : "Voice Agent"}
        </h2>
        <p className="text-slate-500 mt-1">
          {isAr
            ? "إدارة موظف الاستقبال الصوتي بالذكاء الاصطناعي"
            : "Manage your AI voice receptionist"}
        </p>
      </div>
      <button
        onClick={onRefresh}
        disabled={refreshing}
        className="flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-200 text-sm text-slate-600 hover:bg-slate-50 transition-colors disabled:opacity-50"
      >
        <RefreshCw className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`} />
        {isAr ? "تحديث" : "Refresh"}
      </button>
    </div>
  );
}

// ── Upgrade Prompt ───────────────────────────────────────────────────

function UpgradePrompt({ isAr }: { isAr: boolean }) {
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "الوكيل الصوتي" : "Voice Agent"}
          </h2>
          <p className="text-slate-500 mt-1">
            {isAr
              ? "موظف استقبال صوتي بالذكاء الاصطناعي"
              : "AI-powered voice receptionist"}
          </p>
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-slate-200 p-10 text-center shadow-sm">
        <div className="mx-auto w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center mb-5">
          <Lock className="h-8 w-8 text-slate-400" />
        </div>
        <h3 className="text-xl font-bold text-slate-900 mb-2">
          {isAr
            ? "الوكيل الصوتي متاح في خطة الأعمال"
            : "Voice Agent Available on Business Plan"}
        </h3>
        <p className="text-slate-500 max-w-md mx-auto mb-6">
          {isAr
            ? "قم بالترقية إلى خطة الأعمال للحصول على موظف استقبال صوتي ذكي يرد على المكالمات ويحجز المواعيد تلقائياً على مدار الساعة"
            : "Upgrade to the Business plan to get an AI voice receptionist that answers calls and books appointments automatically 24/7"}
        </p>
        <div className="flex flex-wrap justify-center gap-3 mb-8">
          {[
            {
              en: "Answers calls automatically",
              ar: "يرد على المكالمات تلقائياً",
            },
            { en: "Books appointments", ar: "يحجز المواعيد" },
            { en: "Bilingual (AR/EN)", ar: "ثنائي اللغة (عربي/إنجليزي)" },
            { en: "24/7 availability", ar: "متاح على مدار الساعة" },
          ].map((feature) => (
            <span
              key={feature.en}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-50 text-emerald-700 text-sm font-medium"
            >
              <CheckCircle className="h-3.5 w-3.5" />
              {isAr ? feature.ar : feature.en}
            </span>
          ))}
        </div>
        <button className="px-6 py-3 bg-brand-green text-white rounded-xl text-sm font-semibold hover:bg-brand-green/90 transition-colors inline-flex items-center gap-2">
          {isAr ? "ترقية الآن" : "Upgrade Now"}
          <ArrowRight className={`h-4 w-4 ${isAr ? "rotate-180" : ""}`} />
        </button>
      </div>
    </div>
  );
}

// ── Skeleton Loader ──────────────────────────────────────────────────

function SkeletonLoader({ isAr }: { isAr: boolean }) {
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "الوكيل الصوتي" : "Voice Agent"}
          </h2>
          <p className="text-slate-500 mt-1">
            {isAr ? "جاري التحميل..." : "Loading..."}
          </p>
        </div>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {[1, 2, 3, 4].map((i) => (
          <div
            key={i}
            className="bg-white rounded-2xl border border-slate-200 p-6 animate-pulse"
          >
            <div className="h-3 w-20 bg-slate-200 rounded mb-3" />
            <div className="h-7 w-16 bg-slate-200 rounded mb-2" />
            <div className="h-2 w-24 bg-slate-100 rounded" />
          </div>
        ))}
      </div>
      <div className="bg-white rounded-2xl border border-slate-200 p-6 animate-pulse">
        <div className="h-4 w-32 bg-slate-200 rounded mb-4" />
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-12 bg-slate-100 rounded-lg" />
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Provisioned Dashboard ────────────────────────────────────────────

function ProvisionedDashboard({
  isAr,
  agent,
  stats,
  recentCalls,
  onRefresh,
}: {
  isAr: boolean;
  agent: {
    id: string;
    config: VoiceAgentConfig;
    status: string;
    healthStatus: string;
  } | null;
  stats: VoiceAgentStats | null;
  recentCalls: RecentCall[];
  onRefresh: () => Promise<void>;
}) {
  const [activeSubTab, setActiveSubTab] = useState<SubTab>("overview");
  const [refreshing, setRefreshing] = useState(false);

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await onRefresh();
    setRefreshing(false);
  }, [onRefresh]);

  const subTabs: SubTabConfig[] = [
    {
      id: "overview",
      labelEn: "Overview",
      labelAr: "نظرة عامة",
      icon: <Activity className="h-4 w-4" />,
    },
    {
      id: "calls",
      labelEn: "Calls",
      labelAr: "المكالمات",
      icon: <PhoneCall className="h-4 w-4" />,
    },
    {
      id: "settings",
      labelEn: "Settings",
      labelAr: "الإعدادات",
      icon: <Settings className="h-4 w-4" />,
    },
    {
      id: "phone",
      labelEn: "Phone",
      labelAr: "الهاتف",
      icon: <Phone className="h-4 w-4" />,
    },
    {
      id: "analytics",
      labelEn: "Analytics",
      labelAr: "التحليلات",
      icon: <BarChart3 className="h-4 w-4" />,
    },
  ];

  return (
    <div className="space-y-6">
      <PanelHeader
        isAr={isAr}
        onRefresh={handleRefresh}
        refreshing={refreshing}
      />

      {/* Sub-tabs */}
      <div className="flex items-center gap-2 overflow-x-auto pb-1">
        {subTabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveSubTab(tab.id)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all inline-flex items-center gap-2 whitespace-nowrap ${
              activeSubTab === tab.id
                ? "bg-brand-green text-white shadow-sm"
                : "text-slate-600 hover:bg-slate-100"
            }`}
          >
            {tab.icon}
            {isAr ? tab.labelAr : tab.labelEn}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      {activeSubTab === "overview" && (
        <OverviewSubTab
          isAr={isAr}
          stats={stats}
          recentCalls={recentCalls}
          agent={agent}
        />
      )}
      {activeSubTab === "calls" && <CallsSubTab isAr={isAr} />}
      {activeSubTab === "settings" && (
        <SettingsSubTab
          isAr={isAr}
          config={agent?.config ?? null}
          onRefresh={handleRefresh}
        />
      )}
      {activeSubTab === "phone" && (
        <PhoneSubTab isAr={isAr} lang={isAr ? "ar" : "en"} />
      )}
      {activeSubTab === "analytics" && <AnalyticsSubTab isAr={isAr} />}
    </div>
  );
}

// ── Overview Sub-Tab ─────────────────────────────────────────────────

function OverviewSubTab({
  isAr,
  stats,
  recentCalls,
  agent,
}: {
  isAr: boolean;
  stats: VoiceAgentStats | null;
  recentCalls: RecentCall[];
  agent: {
    id: string;
    config: VoiceAgentConfig;
    status: string;
    healthStatus: string;
  } | null;
}) {
  const statCards = [
    {
      labelEn: "Total Calls",
      labelAr: "إجمالي المكالمات",
      value: stats?.totalCalls ?? 0,
      icon: <PhoneCall className="h-5 w-5 text-emerald-600" />,
      gradient: "from-emerald-50 to-teal-50",
      border: "border-emerald-100",
    },
    {
      labelEn: "Today's Calls",
      labelAr: "مكالمات اليوم",
      value: stats?.todayCalls ?? 0,
      icon: <Activity className="h-5 w-5 text-blue-600" />,
      gradient: "from-blue-50 to-indigo-50",
      border: "border-blue-100",
    },
    {
      labelEn: "Avg Duration",
      labelAr: "متوسط المدة",
      value: formatDuration(stats?.avgCallDuration ?? 0),
      icon: <Clock className="h-5 w-5 text-amber-600" />,
      gradient: "from-amber-50 to-orange-50",
      border: "border-amber-100",
    },
    {
      labelEn: "Booked",
      labelAr: "تم الحجز",
      value: stats?.appointmentsBooked ?? 0,
      icon: <CheckCircle className="h-5 w-5 text-violet-600" />,
      gradient: "from-violet-50 to-purple-50",
      border: "border-violet-100",
    },
  ];

  return (
    <div className="space-y-6">
      {/* Status Badge */}
      {agent && (
        <div className="flex items-center gap-3">
          <span
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium ${
              agent.status === "active"
                ? "bg-emerald-50 text-emerald-700 border border-emerald-200/50"
                : "bg-amber-50 text-amber-700 border border-amber-200/50"
            }`}
          >
            <span
              className={`w-2 h-2 rounded-full ${
                agent.status === "active"
                  ? "bg-emerald-500 animate-pulse"
                  : "bg-amber-500"
              }`}
            />
            {agent.status === "active"
              ? isAr
                ? "نشط"
                : "Active"
              : isAr
                ? "غير نشط"
                : "Inactive"}
          </span>
          <span className="text-xs text-slate-400">
            ID: {agent.id.slice(0, 12)}...
          </span>
        </div>
      )}

      {/* Stat Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card) => (
          <div
            key={card.labelEn}
            className={`bg-gradient-to-br ${card.gradient} rounded-2xl border ${card.border} p-5 shadow-sm`}
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs font-medium text-slate-500 uppercase tracking-wide">
                {isAr ? card.labelAr : card.labelEn}
              </span>
              {card.icon}
            </div>
            <p className="text-2xl font-bold text-slate-900">{card.value}</p>
          </div>
        ))}
      </div>

      {/* Recent Calls */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <h3 className="text-lg font-semibold text-slate-900 mb-4">
          {isAr ? "المكالمات الأخيرة" : "Recent Calls"}
        </h3>
        {recentCalls.length === 0 ? (
          <div className="text-center py-8">
            <Phone className="mx-auto h-8 w-8 text-slate-300 mb-2" />
            <p className="text-slate-500 text-sm">
              {isAr ? "لا توجد مكالمات بعد" : "No calls yet"}
            </p>
            <p className="text-slate-400 text-xs mt-1">
              {isAr
                ? "ستظهر المكالمات هنا عند ورودها"
                : "Calls will appear here when they come in"}
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100">
                  <th className="text-start text-xs font-medium text-slate-500 uppercase tracking-wide pb-3 px-2">
                    {isAr ? "العميل" : "Customer"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 uppercase tracking-wide pb-3 px-2">
                    {isAr ? "المدة" : "Duration"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 uppercase tracking-wide pb-3 px-2">
                    {isAr ? "النتيجة" : "Outcome"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 uppercase tracking-wide pb-3 px-2">
                    {isAr ? "الحجز" : "Booking"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 uppercase tracking-wide pb-3 px-2">
                    {isAr ? "الوقت" : "Time"}
                  </th>
                </tr>
              </thead>
              <tbody>
                {recentCalls.slice(0, 5).map((call) => (
                  <tr
                    key={call.id}
                    className="border-b border-slate-50 last:border-0 hover:bg-slate-50/50 transition-colors"
                  >
                    <td className="py-3 px-2">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center flex-shrink-0">
                          <User className="h-4 w-4 text-slate-400" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-slate-900">
                            {call.customerName ||
                              (isAr ? "غير معروف" : "Unknown")}
                          </p>
                          <p className="text-xs text-slate-400">
                            {call.customerPhone || "-"}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="py-3 px-2 text-sm text-slate-600">
                      {formatDuration(call.duration)}
                    </td>
                    <td className="py-3 px-2">
                      <OutcomeBadge outcome={call.outcome} isAr={isAr} />
                    </td>
                    <td className="py-3 px-2">
                      {call.appointmentBooked ? (
                        <span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 bg-emerald-50 px-2 py-1 rounded-full">
                          <CheckCircle className="h-3 w-3" />
                          {isAr ? "نعم" : "Yes"}
                        </span>
                      ) : (
                        <span className="text-xs text-slate-400">-</span>
                      )}
                    </td>
                    <td className="py-3 px-2 text-xs text-slate-500">
                      {formatTimestamp(call.timestamp, isAr)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Calls Sub-Tab ────────────────────────────────────────────────────

function CallsSubTab({ isAr }: { isAr: boolean }) {
  const [conversations, setConversations] = useState<ConversationItem[]>([]);
  const [pagination, setPagination] = useState<ConversationsPagination | null>(
    null,
  );
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [selectedCall, setSelectedCall] = useState<ConversationItem | null>(
    null,
  );

  const fetchConversations = useCallback(
    async (pageNum: number) => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          page: String(pageNum),
          limit: "10",
        });
        if (searchQuery.trim()) {
          params.set("search", searchQuery.trim());
        }
        const res = await fetch(
          `/api/voice-agent/conversations?${params.toString()}`,
          { credentials: "include" },
        );
        if (res.ok) {
          const data = await res.json();
          setConversations(data.conversations || []);
          setPagination(data.pagination || null);
        }
      } catch {
        // silently fail
      } finally {
        setLoading(false);
      }
    },
    [searchQuery],
  );

  // Fetch on mount
  useEffect(() => {
    fetchConversations(page);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSearch = useCallback(() => {
    setPage(1);
    fetchConversations(1);
  }, [fetchConversations]);

  const handlePageChange = useCallback(
    (newPage: number) => {
      setPage(newPage);
      fetchConversations(newPage);
    },
    [fetchConversations],
  );

  return (
    <div className="space-y-4">
      {/* Search Bar */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
            placeholder={
              isAr
                ? "البحث بالاسم أو رقم الهاتف..."
                : "Search by name or phone..."
            }
            className="w-full ps-10 pe-4 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
          />
        </div>
        <button
          onClick={handleSearch}
          className="px-4 py-2.5 bg-brand-green text-white rounded-xl text-sm font-medium hover:bg-brand-green/90 transition-colors"
        >
          {isAr ? "بحث" : "Search"}
        </button>
      </div>

      {/* Calls List */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        {loading ? (
          <div className="p-8 text-center">
            <Loader2 className="mx-auto h-6 w-6 text-slate-400 animate-spin" />
          </div>
        ) : conversations.length === 0 ? (
          <div className="p-8 text-center">
            <PhoneCall className="mx-auto h-8 w-8 text-slate-300 mb-2" />
            <p className="text-slate-500 text-sm">
              {isAr ? "لا توجد مكالمات" : "No calls found"}
            </p>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {conversations.map((conv) => (
              <button
                key={conv.id}
                onClick={() => setSelectedCall(conv)}
                className="w-full text-start p-4 hover:bg-slate-50 transition-colors"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center">
                      <User className="h-5 w-5 text-slate-400" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-slate-900">
                        {conv.customerName ||
                          conv.customerPhone ||
                          (isAr ? "غير معروف" : "Unknown")}
                      </p>
                      <p className="text-xs text-slate-400">
                        {formatTimestamp(conv.startTime, isAr)} &middot;{" "}
                        {formatDuration(conv.durationSeconds)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <CallStatusBadge status={conv.status} isAr={isAr} />
                    {conv.bookingCreated && (
                      <span className="flex items-center gap-1 text-xs text-emerald-600 bg-emerald-50 px-2 py-1 rounded-full">
                        <Calendar className="h-3 w-3" />
                      </span>
                    )}
                  </div>
                </div>
              </button>
            ))}
          </div>
        )}

        {/* Pagination */}
        {pagination && pagination.totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-slate-100">
            <p className="text-xs text-slate-500">
              {isAr
                ? `صفحة ${pagination.page} من ${pagination.totalPages}`
                : `Page ${pagination.page} of ${pagination.totalPages}`}
            </p>
            <div className="flex items-center gap-2">
              <button
                onClick={() => handlePageChange(page - 1)}
                disabled={page <= 1}
                className="px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-40"
              >
                {isAr ? "السابق" : "Previous"}
              </button>
              <button
                onClick={() => handlePageChange(page + 1)}
                disabled={page >= (pagination.totalPages || 1)}
                className="px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-40"
              >
                {isAr ? "التالي" : "Next"}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Transcript Modal */}
      {selectedCall && (
        <TranscriptModal
          call={selectedCall}
          isAr={isAr}
          onClose={() => setSelectedCall(null)}
        />
      )}
    </div>
  );
}

// ── Transcript Modal ─────────────────────────────────────────────────

function TranscriptModal({
  call,
  isAr,
  onClose,
}: {
  call: ConversationItem;
  isAr: boolean;
  onClose: () => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg max-h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-slate-100">
          <div>
            <h3 className="text-lg font-semibold text-slate-900">
              {isAr ? "نص المحادثة" : "Call Transcript"}
            </h3>
            <p className="text-xs text-slate-500 mt-0.5">
              {call.customerName ||
                call.customerPhone ||
                (isAr ? "غير معروف" : "Unknown")}{" "}
              &middot; {formatDuration(call.durationSeconds)}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-slate-100 transition-colors"
          >
            <X className="h-5 w-5 text-slate-400" />
          </button>
        </div>

        {/* Transcript */}
        <div className="flex-1 overflow-y-auto p-5 space-y-3">
          {!call.transcript || call.transcript.length === 0 ? (
            <p className="text-sm text-slate-500 text-center py-4">
              {isAr ? "لا يوجد نص محادثة" : "No transcript available"}
            </p>
          ) : (
            call.transcript.map((entry, idx) => (
              <div
                key={idx}
                className={`flex ${
                  entry.speaker === "agent" ? "justify-start" : "justify-end"
                }`}
              >
                <div
                  className={`max-w-[80%] rounded-2xl px-4 py-2.5 text-sm ${
                    entry.speaker === "agent"
                      ? "bg-slate-100 text-slate-800 rounded-bl-sm"
                      : "bg-brand-green text-white rounded-br-sm"
                  }`}
                >
                  <p>{entry.text}</p>
                  <p
                    className={`text-[10px] mt-1 ${
                      entry.speaker === "agent"
                        ? "text-slate-400"
                        : "text-white/70"
                    }`}
                  >
                    {new Date(entry.timestamp).toLocaleTimeString(
                      isAr ? "ar-SA" : "en-US",
                      { hour: "2-digit", minute: "2-digit" },
                    )}
                  </p>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-slate-100">
          <button
            onClick={onClose}
            className="w-full py-2.5 rounded-xl border border-slate-200 text-sm font-medium text-slate-600 hover:bg-slate-50 transition-colors"
          >
            {isAr ? "إغلاق" : "Close"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Settings Sub-Tab ─────────────────────────────────────────────────

function SettingsSubTab({
  isAr,
  config,
  onRefresh,
}: {
  isAr: boolean;
  config: VoiceAgentConfig | null;
  onRefresh: () => Promise<void>;
}) {
  const [language, setLanguage] = useState<"ar" | "en" | "both">(
    config?.language || "both",
  );
  const [voiceTone, setVoiceTone] = useState<
    "professional" | "friendly" | "custom"
  >(config?.voiceTone || "professional");
  const [greetingEn, setGreetingEn] = useState(
    config?.greetingMessage?.en || "",
  );
  const [greetingAr, setGreetingAr] = useState(
    config?.greetingMessage?.ar || "",
  );
  const [escalationKeywords, setEscalationKeywords] = useState(
    config?.escalationKeywords?.join(", ") || "",
  );
  const [useKB, setUseKB] = useState(config?.useKnowledgeBase ?? true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [settingsSection, setSettingsSection] = useState<
    "basic" | "prompt" | "conversation"
  >("basic");

  // Phase 1: Structured prompt sections
  const [promptSections, setPromptSections] = useState<PromptSections>(
    config?.promptSections ?? {},
  );

  // Phase 1: Conversation & voice settings
  const [conversationSettings, setConversationSettings] =
    useState<ConversationSettings>(config?.conversationSettings ?? {});
  const [voiceSettings, setVoiceSettings] = useState<VoiceSettings>(
    config?.voiceSettings ?? {},
  );

  // Translation keys for the new panels
  const t: Record<string, string> = isAr
    ? {
        vaPromptSections: "التعليمات المنظمة",
        vaPromptSectionsDesc: "حدد سلوك وكيلك عبر أقسام منظمة",
        vaPromptIdentity: "الهوية",
        vaPromptIdentityDesc: "من هو وكيلك وما هو دوره",
        vaPromptIdentityPlaceholder: "أنت مساعد ودود لعيادة...",
        vaPromptStyle: "الأسلوب",
        vaPromptStyleDesc: "كيف يتواصل وكيلك",
        vaPromptStylePlaceholder: "تحدث بلهجة مهنية ودودة...",
        vaPromptResponseGuidelines: "إرشادات الرد",
        vaPromptResponseGuidelinesDesc: "قيود طول الرد وشكله",
        vaPromptResponseGuidelinesPlaceholder: "اجعل الردود أقل من 3 جمل...",
        vaPromptTaskFlow: "سير المهمة",
        vaPromptTaskFlowDesc: "أهداف المحادثة خطوة بخطوة",
        vaPromptTaskFlowPlaceholder: "1. رحب بالعميل 2. اسأل عن احتياجه...",
        vaPromptGuardrails: "الحدود",
        vaPromptGuardrailsDesc: "ما لا يجب على الوكيل فعله أبداً",
        vaPromptGuardrailsPlaceholder: "لا تناقش الأسعار إلا إذا سُئلت...",
        vaPromptTemplateSelect: "اختر قالب صناعة...",
        vaPromptPreview: "معاينة النص الكامل",
        vaConversationSettings: "إعدادات المحادثة",
        vaConversationSettingsDesc: "التحكم في إدارة الأدوار وسير المكالمة",
        vaTurnTimeout: "مهلة الدور",
        vaTurnTimeoutDesc: "أقصى وقت للانتظار قبل المتابعة",
        vaSilenceEndCall: "إنهاء المكالمة عند الصمت",
        vaSilenceEndCallDesc: "إنهاء المكالمة بعد صمت مطول",
        vaInterruptionSensitivity: "حساسية المقاطعة",
        vaInterruptionLow: "منخفضة",
        vaInterruptionHigh: "عالية",
        vaTurnEagerness: "سرعة الاستجابة",
        vaTurnEagernessLow: "بطيئة",
        vaTurnEagernessHigh: "سريعة",
        vaBackchanneling: "الاستجابة التفاعلية",
        vaBackchannelingDesc: "يقول 'أها' و 'حسناً' أثناء حديث المتصل",
        vaBackgroundDenoising: "إزالة الضوضاء",
        vaDenoisingDesc: "تصفية ضوضاء الخلفية في المكالمة",
        vaMaxDuration: "أقصى مدة للمكالمة",
        vaMaxDurationDesc: "الحد الأقصى لمدة المكالمة",
        vaVoiceSettings: "إعدادات الصوت",
        vaVoiceSettingsDesc: "تخصيص خصائص صوت الذكاء الاصطناعي",
        vaVoiceSpeed: "سرعة الصوت",
        vaVoiceSpeedSlower: "أبطأ",
        vaVoiceSpeedFaster: "أسرع",
        vaVoiceStability: "ثبات الصوت",
        vaVoiceStabilityDesc: "ثبات أعلى = صوت أكثر اتساقاً",
        vaVoiceExpressiveness: "تعبيرية الصوت",
        vaVoiceExpressivenessDesc: "تعبيرية أعلى = صوت أكثر حيوية",
      }
    : {
        vaPromptSections: "Structured Prompt",
        vaPromptSectionsDesc:
          "Define your agent behavior with structured sections",
        vaPromptIdentity: "Identity",
        vaPromptIdentityDesc: "Who your agent is and what role it plays",
        vaPromptIdentityPlaceholder:
          "You are a friendly assistant for a clinic...",
        vaPromptStyle: "Style",
        vaPromptStyleDesc: "How your agent communicates",
        vaPromptStylePlaceholder:
          "Speak in a professional yet friendly tone...",
        vaPromptResponseGuidelines: "Response Guidelines",
        vaPromptResponseGuidelinesDesc: "Length and format constraints",
        vaPromptResponseGuidelinesPlaceholder:
          "Keep responses under 3 sentences...",
        vaPromptTaskFlow: "Task Flow",
        vaPromptTaskFlowDesc: "Step-by-step conversation goals",
        vaPromptTaskFlowPlaceholder:
          "1. Greet the customer 2. Ask what they need...",
        vaPromptGuardrails: "Guardrails",
        vaPromptGuardrailsDesc: "What the agent should never do",
        vaPromptGuardrailsPlaceholder: "Never discuss pricing unless asked...",
        vaPromptTemplateSelect: "Select an industry template...",
        vaPromptPreview: "Preview Full Prompt",
        vaConversationSettings: "Conversation Settings",
        vaConversationSettingsDesc:
          "Control how the agent handles turn-taking and call flow",
        vaTurnTimeout: "Turn Timeout",
        vaTurnTimeoutDesc: "Maximum wait time before agent follows up",
        vaSilenceEndCall: "Silence End Call",
        vaSilenceEndCallDesc: "End call after extended silence",
        vaInterruptionSensitivity: "Interruption Sensitivity",
        vaInterruptionLow: "Low",
        vaInterruptionHigh: "High",
        vaTurnEagerness: "Turn Eagerness",
        vaTurnEagernessLow: "Patient",
        vaTurnEagernessHigh: "Eager",
        vaBackchanneling: "Backchannel Responses",
        vaBackchannelingDesc:
          "Agent says 'uh-huh' and 'okay' while caller speaks",
        vaBackgroundDenoising: "Background Denoising",
        vaDenoisingDesc: "Filter out background noise from the call",
        vaMaxDuration: "Max Call Duration",
        vaMaxDurationDesc: "Maximum allowed call length",
        vaVoiceSettings: "Voice Settings",
        vaVoiceSettingsDesc: "Customize the AI voice characteristics",
        vaVoiceSpeed: "Voice Speed",
        vaVoiceSpeedSlower: "Slower",
        vaVoiceSpeedFaster: "Faster",
        vaVoiceStability: "Voice Stability",
        vaVoiceStabilityDesc: "Higher = more consistent voice",
        vaVoiceExpressiveness: "Expressiveness",
        vaVoiceExpressivenessDesc: "Higher = more animated voice",
      };

  const handleSave = useCallback(async () => {
    setSaving(true);
    setSaved(false);
    setSaveError(null);
    try {
      const body = {
        language,
        voiceTone,
        greetingMessage: {
          en: greetingEn || undefined,
          ar: greetingAr || undefined,
        },
        useKnowledgeBase: useKB,
        escalationKeywords: escalationKeywords
          .split(",")
          .map((k) => k.trim())
          .filter(Boolean),
        promptSections,
        conversationSettings,
        voiceSettings,
      };
      const res = await fetchWithCSRF("/api/voice-agent/config", {
        method: "PUT",
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        throw new Error("Failed to update configuration");
      }
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
      await onRefresh();
    } catch (err) {
      setSaveError(
        err instanceof Error ? err.message : "Failed to save settings",
      );
    } finally {
      setSaving(false);
    }
  }, [
    language,
    voiceTone,
    greetingEn,
    greetingAr,
    useKB,
    escalationKeywords,
    promptSections,
    conversationSettings,
    voiceSettings,
    onRefresh,
  ]);

  const sectionTabs = [
    { id: "basic" as const, en: "Basic", ar: "أساسي" },
    { id: "prompt" as const, en: "Prompt", ar: "التعليمات" },
    { id: "conversation" as const, en: "Voice & Flow", ar: "الصوت والتدفق" },
  ];

  return (
    <div className="space-y-4">
      {/* Settings Section Tabs */}
      <div className="flex items-center gap-2 border-b border-slate-200 pb-2">
        {sectionTabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setSettingsSection(tab.id)}
            className={`px-4 py-2 rounded-t-lg text-sm font-medium transition-all ${
              settingsSection === tab.id
                ? "bg-white border border-b-0 border-slate-200 text-slate-900 -mb-[1px]"
                : "text-slate-500 hover:text-slate-700"
            }`}
          >
            {isAr ? tab.ar : tab.en}
          </button>
        ))}
      </div>

      {/* Basic Settings */}
      {settingsSection === "basic" && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-6">
          <h3 className="text-lg font-semibold text-slate-900">
            {isAr ? "إعدادات الوكيل" : "Agent Configuration"}
          </h3>

          {/* Language */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {isAr ? "اللغة" : "Language"}
            </label>
            <div className="flex gap-3">
              {(
                [
                  { value: "both", en: "Both", ar: "كلاهما" },
                  { value: "ar", en: "Arabic", ar: "العربية" },
                  { value: "en", en: "English", ar: "الإنجليزية" },
                ] as const
              ).map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => setLanguage(opt.value)}
                  className={`px-4 py-2 rounded-lg text-sm font-medium border transition-all ${
                    language === opt.value
                      ? "bg-brand-green text-white border-brand-green"
                      : "bg-white text-slate-600 border-slate-200 hover:border-slate-300"
                  }`}
                >
                  {isAr ? opt.ar : opt.en}
                </button>
              ))}
            </div>
          </div>

          {/* Voice Tone */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {isAr ? "نبرة الصوت" : "Voice Tone"}
            </label>
            <div className="flex gap-3">
              {(
                [
                  { value: "professional", en: "Professional", ar: "رسمي" },
                  { value: "friendly", en: "Friendly", ar: "ودي" },
                  { value: "custom", en: "Custom", ar: "مخصص" },
                ] as const
              ).map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => setVoiceTone(opt.value)}
                  className={`px-4 py-2 rounded-lg text-sm font-medium border transition-all ${
                    voiceTone === opt.value
                      ? "bg-brand-green text-white border-brand-green"
                      : "bg-white text-slate-600 border-slate-200 hover:border-slate-300"
                  }`}
                >
                  {isAr ? opt.ar : opt.en}
                </button>
              ))}
            </div>
          </div>

          {/* Greeting Messages */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? "رسالة الترحيب (إنجليزي)" : "Greeting (English)"}
              </label>
              <textarea
                value={greetingEn}
                onChange={(e) => setGreetingEn(e.target.value)}
                rows={3}
                className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green resize-none"
                placeholder="Hello! Thank you for calling..."
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? "رسالة الترحيب (عربي)" : "Greeting (Arabic)"}
              </label>
              <textarea
                value={greetingAr}
                onChange={(e) => setGreetingAr(e.target.value)}
                rows={3}
                dir="rtl"
                className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green resize-none"
                placeholder="مرحباً! شكراً لاتصالك..."
              />
            </div>
          </div>

          {/* Knowledge Base Toggle */}
          <div className="flex items-center justify-between py-3 border-t border-slate-100">
            <div>
              <p className="text-sm font-medium text-slate-700">
                {isAr ? "قاعدة المعرفة" : "Knowledge Base"}
              </p>
              <p className="text-xs text-slate-500 mt-0.5">
                {isAr
                  ? "السماح للوكيل باستخدام قاعدة المعرفة للإجابة على الأسئلة"
                  : "Allow the agent to use your knowledge base for answering questions"}
              </p>
            </div>
            <button
              onClick={() => setUseKB(!useKB)}
              className={`relative w-11 h-6 rounded-full transition-colors ${
                useKB ? "bg-brand-green" : "bg-slate-200"
              }`}
            >
              <span
                className={`absolute top-0.5 start-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                  useKB ? "translate-x-5 rtl:-translate-x-5" : ""
                }`}
              />
            </button>
          </div>

          {/* Escalation Keywords */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {isAr ? "كلمات التصعيد" : "Escalation Keywords"}
            </label>
            <input
              type="text"
              value={escalationKeywords}
              onChange={(e) => setEscalationKeywords(e.target.value)}
              placeholder={
                isAr
                  ? "مدير, شكوى, إلغاء (مفصولة بفاصلة)"
                  : "manager, complaint, cancel (comma-separated)"
              }
              className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
            />
            <p className="text-xs text-slate-500 mt-1">
              {isAr
                ? "عندما يذكر العميل هذه الكلمات، سيتم تحويله لموظف بشري"
                : "When a customer mentions these words, they'll be transferred to a human agent"}
            </p>
          </div>
        </div>
      )}

      {/* Structured Prompt Editor */}
      {settingsSection === "prompt" && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <StructuredPromptEditor
            sections={promptSections}
            onChange={setPromptSections}
            config={
              config ?? {
                language: "both",
                voiceTone: "professional",
                useKnowledgeBase: true,
              }
            }
            t={t}
          />
        </div>
      )}

      {/* Conversation & Voice Settings */}
      {settingsSection === "conversation" && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <ConversationSettingsPanel
            conversationSettings={conversationSettings}
            voiceSettings={voiceSettings}
            onConversationChange={setConversationSettings}
            onVoiceChange={setVoiceSettings}
            t={t}
          />
        </div>
      )}

      {/* Save Button - Always visible */}
      <div className="flex items-center justify-between pt-4">
        <div>
          {saved && (
            <span className="text-sm text-emerald-600 flex items-center gap-1.5">
              <CheckCircle className="h-4 w-4" />
              {isAr ? "تم الحفظ" : "Saved successfully"}
            </span>
          )}
          {saveError && (
            <span className="text-sm text-red-600">{saveError}</span>
          )}
        </div>
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-6 py-2.5 bg-brand-green text-white rounded-xl text-sm font-semibold hover:bg-brand-green/90 transition-colors disabled:opacity-60 inline-flex items-center gap-2"
        >
          {saving ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {isAr ? "جاري الحفظ..." : "Saving..."}
            </>
          ) : (
            <>{isAr ? "حفظ الإعدادات" : "Save Settings"}</>
          )}
        </button>
      </div>
    </div>
  );
}

// ── Phone Sub-Tab ────────────────────────────────────────────────────

function PhoneSubTab({ lang }: { isAr: boolean; lang: Lang }) {
  const [phoneConfig, setPhoneConfig] = useState<PhoneConfigData | null>(null);
  const [loading, setLoading] = useState(true);
  const [fetchKey, setFetchKey] = useState(0);

  useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const res = await fetch("/api/voice-agent/phone", {
          credentials: "include",
        });
        if (res.ok) {
          const data = await res.json();
          setPhoneConfig(data.phoneConfig || null);
        }
      } catch {
        // silently fail
      } finally {
        setLoading(false);
      }
    })();
  }, [fetchKey]);

  if (loading) {
    return (
      <div className="bg-white rounded-2xl border border-slate-200 p-8 text-center animate-pulse">
        <Loader2 className="mx-auto h-6 w-6 text-slate-400 animate-spin" />
      </div>
    );
  }

  return (
    <PhoneConfigPanel
      lang={lang}
      phoneConfig={
        phoneConfig
          ? {
              connectionType: phoneConfig.connectionType as
                | "twilio_native"
                | "custom_sip",
              phoneNumber: phoneConfig.phoneNumber || "",
              isActive: phoneConfig.isActive,
              hasTwilio: Boolean(
                phoneConfig.phoneNumber &&
                phoneConfig.connectionType === "twilio_native",
              ),
              hasSip: Boolean(phoneConfig.connectionType === "custom_sip"),
            }
          : null
      }
      onRefresh={() => setFetchKey((k) => k + 1)}
    />
  );
}

// ── Analytics Sub-Tab ────────────────────────────────────────────────

function AnalyticsSubTab({ isAr }: { isAr: boolean }) {
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState<"7d" | "30d" | "90d">("30d");

  const fetchAnalytics = useCallback(async (p: string) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/voice-agent/analytics?period=${p}`, {
        credentials: "include",
      });
      if (res.ok) {
        const data = await res.json();
        setAnalytics(data.analytics || null);
      }
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAnalytics(period);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handlePeriodChange = useCallback(
    (p: "7d" | "30d" | "90d") => {
      setPeriod(p);
      fetchAnalytics(p);
    },
    [fetchAnalytics],
  );

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="flex gap-2">
          {["7d", "30d", "90d"].map((p) => (
            <div
              key={p}
              className="h-9 w-16 bg-slate-100 rounded-lg animate-pulse"
            />
          ))}
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div
              key={i}
              className="bg-white rounded-2xl border border-slate-200 p-6 animate-pulse"
            >
              <div className="h-3 w-20 bg-slate-200 rounded mb-3" />
              <div className="h-7 w-16 bg-slate-200 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  const cards = [
    {
      labelEn: "Total Calls",
      labelAr: "إجمالي المكالمات",
      value: analytics?.totalCalls ?? 0,
      icon: <PhoneCall className="h-5 w-5 text-emerald-600" />,
      gradient: "from-emerald-50 to-teal-50",
    },
    {
      labelEn: "Success Rate",
      labelAr: "نسبة النجاح",
      value: `${analytics?.successRate ?? 0}%`,
      icon: <CheckCircle className="h-5 w-5 text-blue-600" />,
      gradient: "from-blue-50 to-indigo-50",
    },
    {
      labelEn: "Avg Duration",
      labelAr: "متوسط المدة",
      value: formatDuration(analytics?.avgDurationSeconds ?? 0),
      icon: <Clock className="h-5 w-5 text-amber-600" />,
      gradient: "from-amber-50 to-orange-50",
    },
    {
      labelEn: "Appointments",
      labelAr: "المواعيد المحجوزة",
      value: analytics?.appointmentsBooked ?? 0,
      icon: <Calendar className="h-5 w-5 text-violet-600" />,
      gradient: "from-violet-50 to-purple-50",
    },
    {
      labelEn: "Missed Calls",
      labelAr: "المكالمات الفائتة",
      value: analytics?.missedCalls ?? 0,
      icon: <AlertCircle className="h-5 w-5 text-red-500" />,
      gradient: "from-red-50 to-rose-50",
    },
    {
      labelEn: "Escalated",
      labelAr: "المُصعّدة",
      value: analytics?.escalatedCalls ?? 0,
      icon: <Activity className="h-5 w-5 text-slate-600" />,
      gradient: "from-slate-50 to-gray-50",
    },
  ];

  return (
    <div className="space-y-5">
      {/* Period Selector */}
      <div className="flex items-center gap-2">
        {(
          [
            { value: "7d", en: "7 Days", ar: "7 أيام" },
            { value: "30d", en: "30 Days", ar: "30 يوم" },
            { value: "90d", en: "90 Days", ar: "90 يوم" },
          ] as const
        ).map((opt) => (
          <button
            key={opt.value}
            onClick={() => handlePeriodChange(opt.value)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
              period === opt.value
                ? "bg-brand-green text-white shadow-sm"
                : "text-slate-600 hover:bg-slate-100 border border-slate-200"
            }`}
          >
            {isAr ? opt.ar : opt.en}
          </button>
        ))}
      </div>

      {/* Stat Cards Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {cards.map((card) => (
          <div
            key={card.labelEn}
            className={`bg-gradient-to-br ${card.gradient} rounded-2xl border border-slate-100 p-5 shadow-sm`}
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs font-medium text-slate-500 uppercase tracking-wide">
                {isAr ? card.labelAr : card.labelEn}
              </span>
              {card.icon}
            </div>
            <p className="text-2xl font-bold text-slate-900">{card.value}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Shared UI Components ─────────────────────────────────────────────

function OutcomeBadge({ outcome, isAr }: { outcome: string; isAr: boolean }) {
  const styles: Record<string, string> = {
    completed: "bg-emerald-50 text-emerald-700",
    failed: "bg-red-50 text-red-700",
    escalated: "bg-amber-50 text-amber-700",
  };
  const labels: Record<string, { en: string; ar: string }> = {
    completed: { en: "Completed", ar: "مكتمل" },
    failed: { en: "Failed", ar: "فشل" },
    escalated: { en: "Escalated", ar: "مُصعّد" },
  };
  const style = styles[outcome] || "bg-slate-50 text-slate-700";
  const label = labels[outcome] || { en: outcome, ar: outcome };
  return (
    <span
      className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${style}`}
    >
      {isAr ? label.ar : label.en}
    </span>
  );
}

function CallStatusBadge({
  status,
  isAr,
}: {
  status: "started" | "ended" | "failed";
  isAr: boolean;
}) {
  const config = {
    started: {
      style: "bg-blue-50 text-blue-700",
      en: "In Progress",
      ar: "جارٍ",
    },
    ended: {
      style: "bg-emerald-50 text-emerald-700",
      en: "Completed",
      ar: "مكتمل",
    },
    failed: { style: "bg-red-50 text-red-700", en: "Failed", ar: "فشل" },
  };
  const c = config[status];
  return (
    <span
      className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${c.style}`}
    >
      {isAr ? c.ar : c.en}
    </span>
  );
}

// ── Utility Functions ────────────────────────────────────────────────

function formatDuration(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
}

function formatTimestamp(timestamp: string, isAr: boolean): string {
  try {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));

    if (diffHours < 1) {
      const diffMins = Math.floor(diffMs / (1000 * 60));
      return isAr ? `قبل ${diffMins} دقيقة` : `${diffMins}m ago`;
    }
    if (diffHours < 24) {
      return isAr ? `قبل ${diffHours} ساعة` : `${diffHours}h ago`;
    }

    return date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return timestamp;
  }
}
