"use client";

import { useEffect, useState, useCallback } from "react";
import {
  Bot,
  Zap,
  RefreshCw,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Clock,
  Activity,
  Shield,
  ChevronRight,
  Settings,
  FlaskConical,
  BarChart3,
  Loader2,
} from "lucide-react";
import {
  fetchAIStatus,
  runAIHealthCheck,
  setAIProviderMode,
  fetchAIHealthHistory,
  runDebugTest,
  type AIStatusResponse,
  type ProviderHealth,
  type ProviderHealthExtended,
  type DebugTestResult,
} from "@/lib/api";
import { cn } from "@/lib/utils";

// ── Types ─────────────────────────────────────────────────────────────────────

type ProviderMode = "auto" | "openai" | "gemini" | "claude";

// ── Sub-components ────────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: string }) {
  if (status === "healthy")
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-green-100 text-green-700">
        <CheckCircle2 className="w-3 h-3" /> Healthy
      </span>
    );
  if (status === "down" || status === "error")
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-red-100 text-red-700">
        <XCircle className="w-3 h-3" /> Down
      </span>
    );
  if (status === "unconfigured")
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-gray-100 text-gray-500">
        <AlertTriangle className="w-3 h-3" /> Not Configured
      </span>
    );
  return (
    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-100 text-amber-700">
      <AlertTriangle className="w-3 h-3" /> Unknown
    </span>
  );
}

function ProviderCard({
  provider,
  health,
  isActive,
  logo,
  accentBorder,
  accentBg,
  accentText,
  envVar,
}: {
  provider: string;
  health: ProviderHealthExtended;
  isActive: boolean;
  logo: string;
  accentBorder: string;
  accentBg: string;
  accentText: string;
  envVar: string;
}) {
  const stats = health.stats;
  const successRate = stats?.success_rate ?? 0;
  const calls = stats?.calls ?? 0;

  return (
    <div
      className={`relative bg-white rounded-3xl p-4 sm:p-6 border-2 transition-all duration-300 min-w-0 ${
        isActive ? `${accentBorder} shadow-lg` : "border-gray-100 shadow-sm"
      }`}
    >
      {isActive && (
        <div className={`absolute top-3 right-3 sm:top-4 sm:right-4 px-2 py-0.5 rounded-full text-xs font-black ${accentBg} ${accentText}`}>
          ACTIVE
        </div>
      )}

      <div className="flex items-center gap-3 sm:gap-4 mb-5 pr-14">
        <div className={`w-12 h-12 shrink-0 rounded-2xl flex items-center justify-center text-2xl ${accentBg}`}>
          {logo}
        </div>
        <div className="min-w-0">
          <h3 className="text-sm font-black text-gray-900 capitalize">{provider}</h3>
          <p className="text-xs text-gray-500 truncate" title={health.model || undefined}>{health.model || "—"}</p>
        </div>
      </div>

      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-xs text-gray-500 font-medium">Status</span>
          <StatusBadge status={health.status} />
        </div>

        {health.latency_ms != null && health.latency_ms > 0 && (
          <div className="flex items-center justify-between">
            <span className="text-xs text-gray-500 font-medium">Latency</span>
            <span
              className={`text-xs font-bold ${
                health.latency_ms < 500
                  ? "text-green-600"
                  : health.latency_ms < 1500
                  ? "text-amber-600"
                  : "text-red-600"
              }`}
            >
              {health.latency_ms} ms
            </span>
          </div>
        )}

        {calls > 0 && (
          <>
            <div className="flex items-center justify-between">
              <span className="text-xs text-gray-500 font-medium">Calls</span>
              <span className="text-xs font-bold text-gray-700">{calls}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-xs text-gray-500 font-medium">Success Rate</span>
              <span
                className={`text-xs font-bold ${
                  successRate >= 90
                    ? "text-green-600"
                    : successRate >= 70
                    ? "text-amber-600"
                    : "text-red-600"
                }`}
              >
                {successRate}%
              </span>
            </div>
          </>
        )}

        {health.checkedAt && (
          <div className="flex items-center justify-between">
            <span className="text-xs text-gray-500 font-medium">Last check</span>
            <span className="text-xs text-gray-600">
              {new Date(health.checkedAt).toLocaleTimeString()}
            </span>
          </div>
        )}

        {health.configured === false && (
          <p className="text-xs text-amber-600 bg-amber-50 rounded-xl px-3 py-2 break-words">
            Set {envVar} in .env to enable
          </p>
        )}

        {health.last_error && (
          <p
            className="text-xs text-red-600 bg-red-50 rounded-xl px-3 py-2 break-words"
            title={health.last_error}
          >
            {health.last_error.slice(0, 80)}
          </p>
        )}
      </div>
    </div>
  );
}

// ── Mode selector options ─────────────────────────────────────────────────────

const MODE_OPTIONS: {
  value: ProviderMode;
  label: string;
  desc: string;
  icon: React.ReactNode;
}[] = [
  {
    value: "auto",
    label: "Auto (Recommended)",
    desc: "OpenAI → Gemini → Claude cascade. Light tasks route to Gemini for cost savings.",
    icon: <Zap className="w-4 h-4 text-blue-500" />,
  },
  {
    value: "openai",
    label: "OpenAI Only",
    desc: "Always use OpenAI GPT. No fallback — fails if quota is exhausted.",
    icon: <span className="text-base">🤖</span>,
  },
  {
    value: "gemini",
    label: "Gemini Only",
    desc: "Always use Google Gemini. No fallback — fails if Gemini is down.",
    icon: <span className="text-base">💎</span>,
  },
  {
    value: "claude",
    label: "Claude Only",
    desc: "Always use Anthropic Claude. No fallback — fails if Claude is down.",
    icon: <span className="text-base">🧠</span>,
  },
];

// ══════════════════════════════════════════════════════════════════════════════
// Main page
// ══════════════════════════════════════════════════════════════════════════════

export default function AISettingsPage() {
  const [status, setStatus] = useState<AIStatusResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [checking, setChecking] = useState(false);
  const [settingMode, setSettingMode] = useState(false);
  const [selectedMode, setSelectedMode] = useState<ProviderMode>("auto");
  const [history, setHistory] = useState<
    {
      checkedAt: string;
      mode: string;
      results: Record<string, ProviderHealth>;
    }[]
  >([]);
  const [toast, setToast] = useState<{
    msg: string;
    type: "success" | "error";
  } | null>(null);

  // Debug test state
  const [testPrompt, setTestPrompt] = useState(
    "Write a 3-sentence blog intro about Mahindra Thar"
  );
  const [testResult, setTestResult] = useState<DebugTestResult | null>(null);
  const [testing, setTesting] = useState(false);

  const showToast = (msg: string, type: "success" | "error" = "success") => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 3500);
  };

  const load = useCallback(async () => {
    try {
      const [s, h] = await Promise.all([
        fetchAIStatus(),
        fetchAIHealthHistory(10),
      ]);
      setStatus(s);
      setSelectedMode(s.mode as ProviderMode);
      setHistory(h.records);
    } catch {
      showToast("Failed to load AI status", "error");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const handleHealthCheck = async () => {
    setChecking(true);
    try {
      const result = await runAIHealthCheck();
      showToast(
        `Health check done — OpenAI: ${result.openai?.status}, Gemini: ${result.gemini?.status}, Claude: ${result.claude?.status}`
      );
      await load();
    } catch {
      showToast("Health check failed", "error");
    } finally {
      setChecking(false);
    }
  };

  const handleSetMode = async () => {
    if (!status || selectedMode === status.mode) return;
    setSettingMode(true);
    try {
      await setAIProviderMode(selectedMode);
      showToast(`Mode changed to "${selectedMode}"`);
      await load();
    } catch {
      showToast("Failed to change mode", "error");
    } finally {
      setSettingMode(false);
    }
  };

  const handleDebugTest = async () => {
    setTesting(true);
    setTestResult(null);
    try {
      const result = await runDebugTest(testPrompt, "blog");
      setTestResult(result);
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : "Test failed";
      showToast(msg, "error");
    } finally {
      setTesting(false);
    }
  };

  if (loading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[50vh]">
        <div className="w-8 h-8 rounded-full border-2 border-blue-500 border-t-transparent animate-spin" />
      </div>
    );
  }

  const currentMode = status?.mode ?? "auto";
  const openaiHealth = status?.openai ?? {
    provider: "openai",
    status: "unknown",
    latency_ms: 0,
  };
  const geminiHealth = status?.gemini ?? {
    provider: "gemini",
    status: "unknown",
    latency_ms: 0,
  };
  const claudeHealth = status?.claude ?? {
    provider: "claude",
    status: "unknown",
    latency_ms: 0,
  };

  const allHealthy =
    openaiHealth.status === "healthy" &&
    geminiHealth.status === "healthy" &&
    claudeHealth.status === "healthy";
  const anyDown =
    openaiHealth.status === "down" ||
    geminiHealth.status === "down" ||
    claudeHealth.status === "down";
  const anyConfigured =
    openaiHealth.configured !== false ||
    geminiHealth.configured !== false ||
    claudeHealth.configured !== false;

  return (
    <div className="p-4 sm:p-6 max-w-5xl mx-auto space-y-6">
      {/* Toast */}
      {toast && (
        <div
          className={`fixed top-[calc(1.5rem+env(safe-area-inset-top,0px))] left-4 right-4 sm:left-auto sm:right-6 sm:max-w-sm z-50 px-5 py-3 rounded-2xl text-sm font-semibold shadow-lg transition-all break-words ${
            toast.type === "success"
              ? "bg-green-600 text-white"
              : "bg-red-600 text-white"
          }`}
        >
          {toast.msg}
        </div>
      )}

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-10 h-10 shrink-0 rounded-2xl bg-gradient-to-br from-violet-600 to-blue-500 flex items-center justify-center">
            <Bot className="w-5 h-5 text-white" />
          </div>
          <div className="min-w-0">
            <h1 className="text-xl font-black text-gray-900">
              AI Provider Settings
            </h1>
            <p className="text-sm text-gray-500">
              Universal Fallback — OpenAI → Gemini → Claude
            </p>
          </div>
        </div>
        <button
          onClick={handleHealthCheck}
          disabled={checking}
          className="flex items-center justify-center gap-2 px-4 py-2.5 w-full sm:w-auto bg-white border border-gray-200 rounded-2xl text-sm font-bold text-gray-700 hover:bg-gray-50 transition-all shadow-sm disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${checking ? "animate-spin" : ""}`} />
          {checking ? "Checking…" : "Run Health Check"}
        </button>
      </div>

      {/* Overall status banner */}
      <div
        className={`rounded-3xl p-4 sm:p-5 flex items-start sm:items-center gap-3 sm:gap-4 ${
          allHealthy
            ? "bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200"
            : anyDown
            ? "bg-gradient-to-r from-red-50 to-orange-50 border border-red-200"
            : "bg-gradient-to-r from-amber-50 to-yellow-50 border border-amber-200"
        }`}
      >
        <div
          className={`w-10 h-10 shrink-0 rounded-2xl flex items-center justify-center ${
            allHealthy ? "bg-green-100" : anyDown ? "bg-red-100" : "bg-amber-100"
          }`}
        >
          {allHealthy ? (
            <Shield className="w-5 h-5 text-green-600" />
          ) : anyDown ? (
            <XCircle className="w-5 h-5 text-red-600" />
          ) : (
            <AlertTriangle className="w-5 h-5 text-amber-600" />
          )}
        </div>
        <div className="min-w-0">
          <p
            className={`text-sm font-black ${
              allHealthy
                ? "text-green-800"
                : anyDown
                ? "text-red-800"
                : "text-amber-800"
            }`}
          >
            {allHealthy
              ? "All 3 AI Providers Operational"
              : anyDown
              ? "One or More Providers Down — Failover Active"
              : anyConfigured
              ? "Some Providers Unconfigured — Fallback Ready"
              : "No AI Providers Configured"}
          </p>
          <p
            className={`text-xs mt-0.5 break-words ${
              allHealthy
                ? "text-green-600"
                : anyDown
                ? "text-red-600"
                : "text-amber-600"
            }`}
          >
            Current mode:{" "}
            <strong className="capitalize">{currentMode}</strong>
            {currentMode === "auto" &&
              " — automatic cascade failover enabled (OpenAI → Gemini → Claude)"}
          </p>
        </div>
      </div>

      {/* Provider cards — 3 column grid */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <ProviderCard
          provider="openai"
          health={openaiHealth}
          isActive={
            status?.active === "openai" || currentMode === "openai"
          }
          logo="🤖"
          accentBorder="border-blue-400"
          accentBg="bg-blue-50"
          accentText="text-blue-700"
          envVar="OPENAI_API_KEY"
        />
        <ProviderCard
          provider="gemini"
          health={geminiHealth}
          isActive={
            status?.active === "gemini" || currentMode === "gemini"
          }
          logo="💎"
          accentBorder="border-violet-400"
          accentBg="bg-violet-50"
          accentText="text-violet-700"
          envVar="GEMINI_API_KEY"
        />
        <ProviderCard
          provider="claude"
          health={claudeHealth}
          isActive={
            status?.active === "claude" || currentMode === "claude"
          }
          logo="🧠"
          accentBorder="border-orange-400"
          accentBg="bg-orange-50"
          accentText="text-orange-700"
          envVar="CLAUDE_API_KEY"
        />
      </div>

      {/* Failover flow diagram */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
        <div className="flex items-center gap-2 mb-4">
          <Activity className="w-4 h-4 text-gray-600 shrink-0" />
          <h2 className="text-sm font-black text-gray-900">
            Universal Failover Flow
          </h2>
        </div>
        <div className="flex flex-wrap items-center gap-2 text-sm mb-3">
          <span className="px-3 py-1.5 bg-blue-100 text-blue-800 rounded-xl font-bold">
            1. OpenAI
          </span>
          <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
          <span className="px-3 py-1.5 bg-red-50 text-red-700 rounded-xl font-semibold text-xs">
            fails?
          </span>
          <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
          <span className="px-3 py-1.5 bg-violet-100 text-violet-800 rounded-xl font-bold">
            2. Gemini
          </span>
          <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
          <span className="px-3 py-1.5 bg-red-50 text-red-700 rounded-xl font-semibold text-xs">
            fails?
          </span>
          <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
          <span className="px-3 py-1.5 bg-orange-100 text-orange-800 rounded-xl font-bold">
            3. Claude
          </span>
          <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
          <span className="px-3 py-1.5 bg-green-100 text-green-800 rounded-xl font-bold">
            ✓ Result
          </span>
        </div>
        <p className="text-xs text-gray-500 break-words">
          Failover triggers on: RateLimitError, QuotaExceeded, APITimeoutError,
          APIConnectionError, ServiceUnavailable, ResourceExhausted,
          InvalidAPIKey. All 14 content types (blogs, news, brands, comparisons,
          SEO, FAQs, reviews, guides, etc.) work with every provider.
        </p>
      </div>

      {/* Cost optimisation info */}
      {currentMode === "auto" && (
        <div className="bg-blue-50 border border-blue-100 rounded-3xl p-4 sm:p-5">
          <div className="flex items-center gap-2 mb-3">
            <Zap className="w-4 h-4 text-blue-600 shrink-0" />
            <span className="text-sm font-black text-blue-900">
              Cost Optimisation Active
            </span>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            <div className="bg-white rounded-2xl p-3 border border-blue-100">
              <p className="text-xs font-black text-blue-800 mb-1">
                🤖 OpenAI (heavy tasks)
              </p>
              <ul className="text-xs text-blue-700 space-y-0.5">
                <li>• Blog Generation</li>
                <li>• Car Comparisons</li>
                <li>• Expert Reviews</li>
                <li>• Buying Guides</li>
              </ul>
            </div>
            <div className="bg-white rounded-2xl p-3 border border-violet-100">
              <p className="text-xs font-black text-violet-800 mb-1">
                💎 Gemini (light tasks)
              </p>
              <ul className="text-xs text-violet-700 space-y-0.5">
                <li>• FAQs Generation</li>
                <li>• SEO Metadata</li>
                <li>• Brand Pages</li>
                <li>• News Summaries</li>
              </ul>
            </div>
            <div className="bg-white rounded-2xl p-3 border border-orange-100">
              <p className="text-xs font-black text-orange-800 mb-1">
                🧠 Claude (last resort)
              </p>
              <ul className="text-xs text-orange-700 space-y-0.5">
                <li>• All task types</li>
                <li>• When others fail</li>
                <li>• Emergency fallback</li>
                <li>• Full feature parity</li>
              </ul>
            </div>
          </div>
        </div>
      )}

      {/* Mode selector */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
        <div className="flex items-center gap-2 mb-4">
          <Settings className="w-4 h-4 text-gray-600 shrink-0" />
          <h2 className="text-sm font-black text-gray-900">Provider Mode</h2>
        </div>
        <div className="space-y-3 mb-5">
          {MODE_OPTIONS.map((opt) => (
            <label
              key={opt.value}
              className={`flex items-start gap-3 sm:gap-4 p-3 sm:p-4 rounded-2xl border-2 cursor-pointer transition-all ${
                selectedMode === opt.value
                  ? "border-blue-400 bg-blue-50"
                  : "border-gray-100 hover:border-gray-200"
              }`}
            >
              <input
                type="radio"
                name="mode"
                value={opt.value}
                checked={selectedMode === opt.value}
                onChange={() => setSelectedMode(opt.value)}
                className="mt-1 shrink-0"
              />
              <div className="flex-1 min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  {opt.icon}
                  <span className="text-sm font-bold text-gray-900">
                    {opt.label}
                  </span>
                  {currentMode === opt.value && (
                    <span className="px-1.5 py-0.5 text-[10px] font-black bg-blue-100 text-blue-700 rounded-full">
                      CURRENT
                    </span>
                  )}
                </div>
                <p className="text-xs text-gray-500 mt-1 break-words">{opt.desc}</p>
              </div>
            </label>
          ))}
        </div>
        <button
          onClick={handleSetMode}
          disabled={settingMode || selectedMode === currentMode}
          className="w-full py-3 rounded-2xl text-sm font-black text-white bg-gradient-to-r from-blue-600 to-violet-600 hover:from-blue-700 hover:to-violet-700 disabled:opacity-40 transition-all"
        >
          {settingMode ? "Applying…" : `Apply Mode: ${selectedMode}`}
        </button>
        <p className="text-xs text-gray-400 text-center mt-2">
          Changes take effect immediately. Set AI_PROVIDER in .env for
          persistence across restarts.
        </p>
      </div>

      {/* Debug test panel */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
        <div className="flex flex-wrap items-center gap-2 mb-4">
          <FlaskConical className="w-4 h-4 text-gray-600 shrink-0" />
          <h2 className="text-sm font-black text-gray-900">
            Live Provider Test
          </h2>
          <span className="text-xs text-gray-400 w-full sm:w-auto sm:ml-1">
            — tests the cascade in real-time
          </span>
        </div>
        <div className="flex flex-col sm:flex-row gap-3 mb-4">
          <input
            value={testPrompt}
            onChange={(e) => setTestPrompt(e.target.value)}
            placeholder="Enter a test prompt…"
            className="w-full min-w-0 flex-1 px-4 py-2.5 text-sm border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900"
          />
          <button
            onClick={handleDebugTest}
            disabled={testing || !testPrompt.trim()}
            className="flex items-center justify-center gap-2 px-4 py-2.5 w-full sm:w-auto bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-bold rounded-2xl hover:opacity-90 disabled:opacity-50 transition-all whitespace-nowrap"
          >
            {testing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Zap className="w-4 h-4" />
            )}
            {testing ? "Testing…" : "Run Test"}
          </button>
        </div>

        {testResult && (
          <div
            className={`rounded-2xl p-4 text-sm ${
              testResult.status === "success"
                ? "bg-green-50 border border-green-200"
                : "bg-red-50 border border-red-200"
            }`}
          >
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-3">
              <div className="flex items-center gap-2">
                {testResult.status === "success" ? (
                  <CheckCircle2 className="w-4 h-4 text-green-600 shrink-0" />
                ) : (
                  <XCircle className="w-4 h-4 text-red-600 shrink-0" />
                )}
                <span
                  className={`font-black ${
                    testResult.status === "success"
                      ? "text-green-800"
                      : "text-red-800"
                  }`}
                >
                  {testResult.status === "success" ? "Success" : "Failed"}
                </span>
              </div>
              <div className="flex flex-wrap items-center gap-2 text-xs">
                {testResult.provider !== "none" && (
                  <span className="px-2 py-1 bg-white rounded-xl font-bold text-gray-700 border border-gray-200">
                    Provider:{" "}
                    <span className="capitalize">{testResult.provider}</span>
                  </span>
                )}
                {testResult.model && testResult.provider !== "none" && (
                  <span className="px-2 py-1 bg-white rounded-xl font-semibold text-gray-600 border border-gray-200 break-all">
                    {testResult.model}
                  </span>
                )}
                {testResult.latency_ms && (
                  <span className="px-2 py-1 bg-white rounded-xl font-semibold text-gray-600 border border-gray-200">
                    {testResult.latency_ms}ms
                  </span>
                )}
                {testResult.tokens_generated && (
                  <span className="px-2 py-1 bg-white rounded-xl font-semibold text-gray-600 border border-gray-200">
                    {testResult.tokens_generated} tokens
                  </span>
                )}
              </div>
            </div>

            {testResult.content && (
              <div className="bg-white rounded-xl p-3 border border-green-100 text-gray-700 text-xs leading-relaxed max-h-32 overflow-y-auto break-words">
                {testResult.content}
              </div>
            )}
            {testResult.error && (
              <p className="text-red-700 text-xs mt-1 break-words">{testResult.error}</p>
            )}
          </div>
        )}
      </div>

      {/* Provider stats */}
      {status && (
        <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
          <div className="flex flex-wrap items-center gap-2 mb-4">
            <BarChart3 className="w-4 h-4 text-gray-600 shrink-0" />
            <h2 className="text-sm font-black text-gray-900">
              Provider Usage Stats
            </h2>
            <span className="text-xs text-gray-400 w-full sm:w-auto">
              (since last server restart)
            </span>
          </div>
          <div className="grid grid-cols-1 xs:grid-cols-3 sm:grid-cols-3 gap-3 sm:gap-4">
            {(["openai", "gemini", "claude"] as const).map((p) => {
              const h = status[p];
              const s = h?.stats;
              return (
                <div
                  key={p}
                  className="text-center p-3 sm:p-4 bg-gray-50 rounded-2xl min-w-0"
                >
                  <div className="text-2xl mb-1">
                    {p === "openai" ? "🤖" : p === "gemini" ? "💎" : "🧠"}
                  </div>
                  <div className="text-xs font-black text-gray-700 capitalize mb-2">
                    {p}
                  </div>
                  <div className="text-lg font-black text-gray-900">
                    {s?.calls ?? 0}
                  </div>
                  <div className="text-xs text-gray-500">calls</div>
                  <div
                    className={`text-xs font-bold mt-1 ${
                      (s?.success_rate ?? 0) >= 90
                        ? "text-green-600"
                        : (s?.success_rate ?? 0) >= 70
                        ? "text-amber-600"
                        : "text-red-600"
                    }`}
                  >
                    {s?.calls ? `${s.success_rate}% success` : "no data"}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Health history */}
      {history.length > 0 && (
        <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
          <div className="flex items-center gap-2 mb-4">
            <Clock className="w-4 h-4 text-gray-600 shrink-0" />
            <h2 className="text-sm font-black text-gray-900">
              Recent Health Checks
            </h2>
          </div>
          <div className="overflow-x-auto -mx-1 px-1">
            <table className="w-full text-xs min-w-[520px]">
              <thead>
                <tr className="text-gray-400 font-semibold border-b border-gray-100">
                  <th className="text-left pb-2 pr-4">Time</th>
                  <th className="text-left pb-2 pr-4">Mode</th>
                  <th className="text-left pb-2 pr-3">OpenAI</th>
                  <th className="text-left pb-2 pr-3">Gemini</th>
                  <th className="text-left pb-2">Claude</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {history.map((rec, i) => (
                  <tr key={i} className="hover:bg-gray-50">
                    <td className="py-2 pr-4 text-gray-600 whitespace-nowrap">
                      {new Date(rec.checkedAt).toLocaleString()}
                    </td>
                    <td className="py-2 pr-4 font-semibold text-gray-700 capitalize">
                      {rec.mode}
                    </td>
                    <td className="py-2 pr-3">
                      <StatusBadge
                        status={rec.results?.openai?.status ?? "unknown"}
                      />
                    </td>
                    <td className="py-2 pr-3">
                      <StatusBadge
                        status={rec.results?.gemini?.status ?? "unknown"}
                      />
                    </td>
                    <td className="py-2">
                      <StatusBadge
                        status={rec.results?.claude?.status ?? "unknown"}
                      />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Supported features */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-4 sm:p-6">
        <h2 className="text-sm font-black text-gray-900 mb-4">
          All Features — Supported by Every Provider
        </h2>
        <div className="grid grid-cols-1 xs:grid-cols-2 sm:grid-cols-3 gap-2">
          {[
            "Blog Generation",
            "News Generation",
            "Brand Pages",
            "Comparison Pages",
            "SEO Metadata",
            "FAQs",
            "Expert Reviews",
            "Ownership Guides",
            "Buying Guides",
            "AI Search Responses",
            "Car Recommendations",
            "Topic Clusters",
            "Programmatic SEO",
            "Lead Intelligence",
          ].map((feat) => (
            <div key={feat} className="flex items-center gap-2 text-xs text-gray-700 min-w-0">
              <CheckCircle2 className="w-3.5 h-3.5 text-green-500 shrink-0" />
              <span className="min-w-0 break-words">{feat}</span>
            </div>
          ))}
        </div>
        <p className="text-xs text-gray-400 mt-3">
          All features work identically regardless of which provider is active.
          No feature is provider-specific.
        </p>
      </div>
    </div>
  );
}
