"use client";

/**
 * /admin/ai-generator — AI Data Generator
 *
 * One-click "Initialize DriveHub" or granular per-entity generation.
 * Polls GET /api/ai-generator/status every 3 s while an operation is in flight.
 */

import { useCallback, useEffect, useRef, useState } from "react";
import {
  Sparkles, Car, Tag, ListChecks, HelpCircle, Star,
  GitCompare, FileText, Zap, RefreshCw, CheckCircle2,
  AlertCircle, Loader2, BarChart2, Info, Play, Clock,
  ChevronDown, ChevronUp, ImageIcon, Settings,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { getAdminToken } from "@/lib/adminAuth";
import {
  fetchCarImageSource,
  setCarImageSource,
  type CarImageSource,
  type CarImageSourceSettings,
} from "@/lib/api";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";

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

interface SeedState {
  running:      boolean;
  operation:    string | null;
  progress:     number;
  total:        number;
  inserted:     number;
  updated:      number;
  errors:       number;
  last_result:  Record<string, any> | null;
  last_error:   string | null;
  completed_at: string | null;
}

interface DBStats {
  total_cars:   number;
  ai_cars:      number;
  total_brands: number;
  brand_pages:  number;
  total_blogs:  number;
  comparisons:  number;
  brand_counts: Record<string, number>;
}

interface StatusResponse {
  seed:     SeedState;
  database: DBStats;
  catalog:  { available_brands: string[]; catalog_size: number };
}

// ── API helpers ────────────────────────────────────────────────────────────────

async function apiFetch(path: string, method = "GET", body?: unknown) {
  const token = getAdminToken();
  const res = await fetch(`${API}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    ...(body ? { body: JSON.stringify(body) } : {}),
  });
  if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.detail ?? `HTTP ${res.status}`); }
  return res.json();
}

// ── Stat card ─────────────────────────────────────────────────────────────────

function StatCard({ label, value, icon: Icon, color }: {
  label: string; value: string | number;
  icon: React.ComponentType<{ className?: string }>; color: string;
}) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center gap-3">
      <div className={cn("w-10 h-10 rounded-xl flex items-center justify-center shrink-0", color)}>
        <Icon className="w-5 h-5 text-white" />
      </div>
      <div>
        <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">{label}</p>
        <p className="text-xl font-black text-gray-900">{value}</p>
      </div>
    </div>
  );
}

// ── Action button ─────────────────────────────────────────────────────────────

function ActionButton({
  label, icon: Icon, description, color, loading, disabled, onClick,
}: {
  label: string; icon: React.ComponentType<{ className?: string }>;
  description: string; color: string;
  loading?: boolean; disabled?: boolean; onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      disabled={disabled || loading}
      className={cn(
        "group w-full flex items-start gap-3 p-4 rounded-2xl border-2 text-left transition-all duration-200",
        "hover:shadow-md active:scale-[0.98]",
        disabled || loading
          ? "border-gray-100 bg-gray-50 cursor-not-allowed opacity-60"
          : "border-gray-100 bg-white hover:border-current cursor-pointer",
        !disabled && !loading && color,
      )}
    >
      <div className={cn(
        "w-9 h-9 rounded-xl flex items-center justify-center shrink-0 transition-colors",
        disabled || loading ? "bg-gray-100" : "bg-current/10"
      )}>
        {loading
          ? <Loader2 className="w-4 h-4 animate-spin text-gray-400" />
          : <Icon className="w-4 h-4" />
        }
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-black leading-tight">{label}</p>
        <p className="text-xs text-gray-400 mt-0.5 leading-snug">{description}</p>
      </div>
      {!loading && !disabled && <Play className="w-3.5 h-3.5 shrink-0 mt-1 opacity-40 group-hover:opacity-100 transition-opacity" />}
    </button>
  );
}

// ── Progress bar ──────────────────────────────────────────────────────────────

function ProgressBar({ value, total, label }: { value: number; total: number; label: string }) {
  const pct = total > 0 ? Math.round((value / total) * 100) : 0;
  return (
    <div>
      <div className="flex flex-wrap items-center justify-between gap-x-2 gap-y-0.5 mb-1.5">
        <span className="text-xs font-bold text-gray-600">{label}</span>
        <span className="text-xs text-gray-400 shrink-0">{value} / {total} ({pct}%)</span>
      </div>
      <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
        <div
          className="h-full bg-gradient-to-r from-violet-500 to-blue-500 rounded-full transition-all duration-500"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}

// ── Main page ─────────────────────────────────────────────────────────────────

export default function AIGeneratorPage() {
  const [status,      setStatus]      = useState<StatusResponse | null>(null);
  const [loading,     setLoading]     = useState(true);
  const [toast,       setToast]       = useState<{ msg: string; ok: boolean } | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [brandsOpen,  setBrandsOpen]  = useState(false);
  const [resultOpen,  setResultOpen]  = useState(false);

  // Cars form state
  const [carBrand,     setCarBrand]     = useState("");
  const [carCount,     setCarCount]     = useState(8);
  const [carEnrich,    setCarEnrich]    = useState(true);
  const [blogCount,    setBlogCount]    = useState(10);
  const [compCount,    setCompCount]    = useState(20);
  const [subLimit,     setSubLimit]     = useState(50);

  // Specific car form state
  const [specBrand,    setSpecBrand]    = useState("");
  const [specCar,      setSpecCar]      = useState("");
  const [specYear,     setSpecYear]     = useState<number | "">("");
  const [specVariants, setSpecVariants] = useState(true);
  const [specReviews,  setSpecReviews]  = useState(true);
  const [specFaqs,     setSpecFaqs]     = useState(true);
  const [specComps,    setSpecComps]    = useState(false);
  const [specSeo,      setSpecSeo]      = useState(true);

  // Image source settings
  const [imgSource,     setImgSource]     = useState<CarImageSource>("google");
  const [imgProviders,  setImgProviders]  = useState<CarImageSourceSettings["providers"] | null>(null);
  const [imgSaving,     setImgSaving]     = useState(false);

  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const showToast = (msg: string, ok = true) => {
    setToast({ msg, ok });
    setTimeout(() => setToast(null), 4000);
  };

  const loadStatus = useCallback(async () => {
    try {
      const data = await apiFetch("/api/ai-generator/status");
      setStatus(data);
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, []);

  // Poll every 3 s while an operation is running
  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  useEffect(() => {
    fetchCarImageSource()
      .then((data) => {
        setImgSource(data.source);
        setImgProviders(data.providers);
      })
      .catch(() => { /* ignore — settings optional */ });
  }, []);

  const saveImageSource = async (source: CarImageSource) => {
    setImgSaving(true);
    try {
      const res = await setCarImageSource(source);
      setImgSource(res.current as CarImageSource);
      showToast(res.message);
      const refreshed = await fetchCarImageSource();
      setImgProviders(refreshed.providers);
    } catch (e: unknown) {
      showToast(e instanceof Error ? e.message : "Failed to save image source", false);
    } finally {
      setImgSaving(false);
    }
  };

  useEffect(() => {
    if (status?.seed?.running) {
      if (!pollRef.current) {
        pollRef.current = setInterval(loadStatus, 3000);
      }
    } else {
      if (pollRef.current) {
        clearInterval(pollRef.current);
        pollRef.current = null;
      }
    }
    return () => { if (pollRef.current) clearInterval(pollRef.current); };
  }, [status?.seed?.running, loadStatus]);

  const isRunning = status?.seed?.running ?? false;

  async function runAction(
    path: string,
    method: string,
    body: unknown,
    label: string,
  ) {
    if (isRunning) { showToast("Another operation is already running", false); return; }
    setActionLoading(label);
    try {
      const res = await apiFetch(path, method, body);
      showToast(res.message ?? `${label} started`);
      await loadStatus();
    } catch (e: any) {
      showToast(e.message, false);
    } finally {
      setActionLoading(null);
    }
  }

  const db    = status?.database;
  const seed  = status?.seed;
  const cat   = status?.catalog;

  return (
    <div className="p-4 sm:p-6 max-w-[1200px] mx-auto space-y-6 min-w-0">

      {/* ── Header ── */}
      <div className="flex flex-col xs:flex-row xs:items-center justify-between gap-4">
        <div className="min-w-0">
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
            <Sparkles className="w-6 h-6 text-violet-500 shrink-0" />
            AI Data Generator
          </h1>
          <p className="text-sm text-gray-400 mt-0.5">
            Seed DriveHub with AI-generated car data — no scraper required
          </p>
        </div>
        <button
          onClick={() => { setLoading(true); loadStatus(); }}
          className="flex items-center justify-center gap-1.5 w-full xs:w-auto px-4 py-2.5 text-sm font-bold text-gray-600 bg-white border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors shadow-sm shrink-0"
        >
          <RefreshCw className={cn("w-3.5 h-3.5", loading && "animate-spin")} />
          Refresh
        </button>
      </div>

      {/* ── Toast ── */}
      {toast && (
        <div className={cn(
          "flex items-start sm:items-center gap-2 px-4 py-3 rounded-xl text-sm font-semibold border",
          toast.ok ? "bg-green-50 text-green-700 border-green-200"
                   : "bg-red-50 text-red-700 border-red-200"
        )}>
          {toast.ok ? <CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5 sm:mt-0" /> : <AlertCircle className="w-4 h-4 shrink-0 mt-0.5 sm:mt-0" />}
          <p className="flex-1 min-w-0 break-words">{toast.msg}</p>
        </div>
      )}

      {/* ── Live progress ── */}
      {isRunning && seed && (
        <div className="bg-violet-50 border border-violet-200 rounded-2xl p-5 space-y-3">
          <div className="flex items-center gap-2 min-w-0">
            <Loader2 className="w-4 h-4 text-violet-600 animate-spin shrink-0" />
            <p className="text-sm font-black text-violet-800 capitalize min-w-0 break-words">
              {seed.operation} generation in progress…
            </p>
          </div>
          {seed.total > 0 && (
            <ProgressBar value={seed.progress} total={seed.total} label="Progress" />
          )}
          <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-violet-600 font-semibold">
            <span>✅ {seed.inserted} inserted</span>
            <span>🔄 {seed.updated} updated</span>
            {seed.errors > 0 && <span className="text-red-600">❌ {seed.errors} errors</span>}
          </div>
        </div>
      )}

      {/* ── DB Stats ── */}
      {db && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <StatCard label="Total Cars"   value={db.total_cars}   icon={Car}       color="bg-blue-500" />
          <StatCard label="AI Generated" value={db.ai_cars}      icon={Sparkles}  color="bg-violet-500" />
          <StatCard label="Brands"       value={db.total_brands} icon={Tag}       color="bg-orange-500" />
          <StatCard label="Blog Posts"   value={db.total_blogs}  icon={FileText}  color="bg-green-500" />
        </div>
      )}

      {/* ── Initialize DriveHub (hero CTA) ── */}
      <div className="bg-gradient-to-br from-violet-600 via-blue-600 to-cyan-500 rounded-3xl p-6 text-white shadow-xl">
        <div className="flex flex-col sm:flex-row sm:items-center gap-4">
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <Zap className="w-5 h-5" />
              <h2 className="text-lg font-black">Initialize DriveHub</h2>
            </div>
            <p className="text-sm text-white/80 leading-snug">
              Generate all data in one click: brands → cars → variants → FAQs → reviews → comparisons → blogs.
              Uses AI (Gemini/OpenAI/Claude). Takes 15–45 minutes.
            </p>
            <div className="flex items-center gap-3 mt-2">
              <label className="flex items-center gap-1.5 text-xs font-semibold cursor-pointer">
                <input
                  type="checkbox"
                  checked={carEnrich}
                  onChange={(e) => setCarEnrich(e.target.checked)}
                  className="rounded"
                />
                AI Enrichment (specs/variants/FAQs)
              </label>
            </div>
          </div>
          <div className="flex flex-col gap-2 w-full sm:w-auto shrink-0">
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction(
                "/api/ai-generator/initialize", "POST",
                { skip_if_populated: false, enrich_with_ai: carEnrich },
                "Initialize DriveHub",
              )}
              className="flex items-center justify-center gap-2 w-full sm:w-auto px-6 py-3 bg-white text-violet-700 font-black rounded-2xl hover:bg-violet-50 transition-colors shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "Initialize DriveHub"
                ? <Loader2 className="w-4 h-4 animate-spin" />
                : <Zap className="w-4 h-4" />
              }
              Initialize DriveHub
            </button>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction("/api/ai-generator/initialize-quick", "POST", undefined, "Quick Seed")}
              className="flex items-center justify-center gap-2 w-full sm:w-auto px-6 py-2.5 bg-white/20 hover:bg-white/30 text-white font-bold rounded-xl transition-colors text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Car className="w-3.5 h-3.5" />
              Quick Seed (No AI, instant)
            </button>
          </div>
        </div>
      </div>

      {/* ── Generate Specific Car ── */}
      <div className="bg-white rounded-3xl border-2 border-violet-100 shadow-sm p-5 sm:p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-2xl bg-violet-100 flex items-center justify-center">
            <Car className="w-5 h-5 text-violet-600" />
          </div>
          <div>
            <h2 className="text-base font-black text-gray-900">Generate Specific Car</h2>
            <p className="text-xs text-gray-400">
              AI-generate one car for a brand and save it to the database
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
          <div>
            <label className="text-[10px] font-bold text-gray-400 uppercase">Brand Name *</label>
            <input
              value={specBrand}
              onChange={(e) => setSpecBrand(e.target.value)}
              placeholder="Tesla"
              className="w-full mt-1 text-sm border border-gray-200 rounded-xl px-3 py-2 focus:outline-none focus:ring-2 focus:ring-violet-300 font-semibold"
            />
          </div>
          <div>
            <label className="text-[10px] font-bold text-gray-400 uppercase">Car Name *</label>
            <input
              value={specCar}
              onChange={(e) => setSpecCar(e.target.value)}
              placeholder="Model 3"
              className="w-full mt-1 text-sm border border-gray-200 rounded-xl px-3 py-2 focus:outline-none focus:ring-2 focus:ring-violet-300 font-semibold"
            />
          </div>
          <div>
            <label className="text-[10px] font-bold text-gray-400 uppercase">Year (optional)</label>
            <input
              type="number"
              min={2018}
              max={2030}
              value={specYear}
              onChange={(e) => setSpecYear(e.target.value ? Number(e.target.value) : "")}
              placeholder="2024"
              className="w-full mt-1 text-sm border border-gray-200 rounded-xl px-3 py-2 focus:outline-none focus:ring-2 focus:ring-violet-300 font-semibold"
            />
          </div>
        </div>

        <div className="flex flex-wrap gap-x-5 gap-y-2">
          {([
            ["Generate Variants", specVariants, setSpecVariants],
            ["Generate Reviews", specReviews, setSpecReviews],
            ["Generate FAQs", specFaqs, setSpecFaqs],
            ["Generate Comparisons", specComps, setSpecComps],
            ["Generate SEO Content", specSeo, setSpecSeo],
          ] as const).map(([label, checked, setter]) => (
            <label key={label} className="flex items-center gap-1.5 text-xs font-semibold text-gray-600 cursor-pointer">
              <input
                type="checkbox"
                checked={checked}
                onChange={(e) => setter(e.target.checked)}
                className="rounded"
              />
              {label}
            </label>
          ))}
        </div>

        <button
          disabled={actionLoading !== null || !specBrand.trim() || !specCar.trim()}
          onClick={() => runAction(
            "/api/ai-generator/specific-car",
            "POST",
            {
              brand_name: specBrand.trim(),
              car_name: specCar.trim(),
              year: specYear || null,
              generate_variants: specVariants,
              generate_reviews: specReviews,
              generate_faqs: specFaqs,
              generate_comparisons: specComps,
              generate_seo_content: specSeo,
            },
            "specific-car",
          )}
          className="flex items-center justify-center gap-2 w-full sm:w-auto px-6 py-3 bg-violet-600 hover:bg-violet-700 text-white text-sm font-black rounded-2xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {actionLoading === "specific-car"
            ? <Loader2 className="w-4 h-4 animate-spin" />
            : <Sparkles className="w-4 h-4" />
          }
          Generate Car
        </button>
      </div>

      {/* ── Individual buttons ── */}
      <div>
        <h3 className="text-sm font-black text-gray-600 uppercase tracking-wider mb-3">
          Individual Generators
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">

          {/* Brands */}
          <ActionButton
            label="Generate Brands"
            icon={Tag}
            description="Generate brand overview pages for all 15 Indian car brands"
            color="text-orange-600"
            loading={actionLoading === "brands"}
            disabled={isRunning}
            onClick={() => runAction("/api/ai-generator/brands", "POST", undefined, "brands")}
          />

          {/* Cars */}
          <div className="bg-white rounded-2xl border-2 border-gray-100 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-blue-50 flex items-center justify-center">
                <Car className="w-4 h-4 text-blue-600" />
              </div>
              <div>
                <p className="text-sm font-black text-blue-600">Generate Cars</p>
                <p className="text-xs text-gray-400">AI-generate car listings</p>
              </div>
            </div>
            <div className="space-y-2">
              <select
                value={carBrand}
                onChange={(e) => setCarBrand(e.target.value)}
                className="w-full text-xs border border-gray-200 rounded-xl px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-400 font-semibold text-gray-700"
              >
                <option value="">All Brands</option>
                {(cat?.available_brands ?? []).map((b) => <option key={b} value={b}>{b}</option>)}
              </select>
              <div className="flex gap-2">
                <div className="flex-1">
                  <label className="text-[10px] font-bold text-gray-400">Cars / brand</label>
                  <input
                    type="number" min={1} max={15} value={carCount}
                    onChange={(e) => setCarCount(Number(e.target.value))}
                    className="w-full text-xs border border-gray-200 rounded-xl px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-400 font-semibold"
                  />
                </div>
                <label className="flex items-center gap-1 text-xs font-semibold text-gray-600 mt-4 cursor-pointer">
                  <input type="checkbox" checked={carEnrich} onChange={(e) => setCarEnrich(e.target.checked)} />
                  AI
                </label>
              </div>
            </div>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction(
                "/api/ai-generator/cars", "POST",
                { brand: carBrand || null, count_per_brand: carCount, enrich_with_ai: carEnrich },
                "cars",
              )}
              className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-black text-white bg-blue-600 hover:bg-blue-700 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "cars" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              Generate Cars
            </button>
          </div>

          {/* Variants */}
          <div className="bg-white rounded-2xl border-2 border-gray-100 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-green-50 flex items-center justify-center">
                <ListChecks className="w-4 h-4 text-green-600" />
              </div>
              <div>
                <p className="text-sm font-black text-green-600">Generate Variants</p>
                <p className="text-xs text-gray-400">Fill empty variant arrays</p>
              </div>
            </div>
            <div>
              <label className="text-[10px] font-bold text-gray-400">Cars to process</label>
              <input
                type="number" min={1} max={200} value={subLimit}
                onChange={(e) => setSubLimit(Number(e.target.value))}
                className="w-full text-xs border border-gray-200 rounded-xl px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-green-400 font-semibold mt-1"
              />
            </div>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction("/api/ai-generator/variants", "POST", { limit: subLimit }, "variants")}
              className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-black text-white bg-green-600 hover:bg-green-700 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "variants" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              Generate Variants
            </button>
          </div>

          {/* Reviews */}
          <ActionButton
            label="Generate Reviews"
            icon={Star}
            description="Update ratings & review counts for all cars (instant, no AI)"
            color="text-amber-600"
            loading={actionLoading === "reviews"}
            disabled={isRunning}
            onClick={() => runAction("/api/ai-generator/reviews", "POST", undefined, "reviews")}
          />

          {/* FAQs */}
          <div className="bg-white rounded-2xl border-2 border-gray-100 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-purple-50 flex items-center justify-center">
                <HelpCircle className="w-4 h-4 text-purple-600" />
              </div>
              <div>
                <p className="text-sm font-black text-purple-600">Generate FAQs</p>
                <p className="text-xs text-gray-400">Fill empty FAQs with AI Q&A</p>
              </div>
            </div>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction("/api/ai-generator/faqs", "POST", { limit: subLimit }, "faqs")}
              className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-black text-white bg-purple-600 hover:bg-purple-700 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "faqs" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              Generate FAQs
            </button>
          </div>

          {/* Comparisons */}
          <div className="bg-white rounded-2xl border-2 border-gray-100 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-cyan-50 flex items-center justify-center">
                <GitCompare className="w-4 h-4 text-cyan-600" />
              </div>
              <div>
                <p className="text-sm font-black text-cyan-600">Generate Comparisons</p>
                <p className="text-xs text-gray-400">AI comparison verdict pages</p>
              </div>
            </div>
            <div>
              <label className="text-[10px] font-bold text-gray-400">Count</label>
              <input
                type="number" min={1} max={50} value={compCount}
                onChange={(e) => setCompCount(Number(e.target.value))}
                className="w-full text-xs border border-gray-200 rounded-xl px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-cyan-400 font-semibold mt-1"
              />
            </div>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction("/api/ai-generator/comparisons", "POST", { count: compCount }, "comparisons")}
              className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-black text-white bg-cyan-600 hover:bg-cyan-700 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "comparisons" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              Generate Comparisons
            </button>
          </div>

          {/* Blogs */}
          <div className="bg-white rounded-2xl border-2 border-gray-100 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-rose-50 flex items-center justify-center">
                <FileText className="w-4 h-4 text-rose-600" />
              </div>
              <div>
                <p className="text-sm font-black text-rose-600">Generate Blogs</p>
                <p className="text-xs text-gray-400">AI blog posts published instantly</p>
              </div>
            </div>
            <div>
              <label className="text-[10px] font-bold text-gray-400">Count</label>
              <input
                type="number" min={1} max={50} value={blogCount}
                onChange={(e) => setBlogCount(Number(e.target.value))}
                className="w-full text-xs border border-gray-200 rounded-xl px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-rose-400 font-semibold mt-1"
              />
            </div>
            <button
              disabled={isRunning || actionLoading !== null}
              onClick={() => runAction("/api/ai-generator/blogs", "POST", { count: blogCount }, "blogs")}
              className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-black text-white bg-rose-600 hover:bg-rose-700 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {actionLoading === "blogs" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              Generate Blogs
            </button>
          </div>

        </div>
      </div>

      {/* ── Brand coverage ── */}
      {db?.brand_counts && Object.keys(db.brand_counts).length > 0 && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm">
          <button
            onClick={() => setBrandsOpen((o) => !o)}
            className="w-full flex items-center justify-between gap-3 px-4 sm:px-5 py-4 hover:bg-gray-50 transition-colors rounded-2xl"
          >
            <div className="flex items-center gap-2 min-w-0 flex-1 flex-wrap">
              <BarChart2 className="w-4 h-4 text-gray-400 shrink-0" />
              <span className="text-sm font-black text-gray-700">Brand Coverage</span>
              <span className="text-xs bg-gray-100 text-gray-500 font-bold px-2 py-0.5 rounded-full shrink-0">
                {Object.keys(db.brand_counts).length} brands
              </span>
            </div>
            {brandsOpen ? <ChevronUp className="w-4 h-4 text-gray-400 shrink-0" /> : <ChevronDown className="w-4 h-4 text-gray-400 shrink-0" />}
          </button>
          {brandsOpen && (
            <div className="px-5 pb-5 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
              {Object.entries(db.brand_counts)
                .sort(([, a], [, b]) => b - a)
                .map(([brand, count]) => (
                  <div key={brand} className="bg-gray-50 rounded-xl p-2.5 flex items-center justify-between">
                    <span className="text-xs font-bold text-gray-700 truncate">{brand}</span>
                    <span className="text-xs font-black text-blue-600 ml-1 shrink-0">{count}</span>
                  </div>
                ))}
            </div>
          )}
        </div>
      )}

      {/* ── Last result ── */}
      {seed?.last_result && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm">
          <button
            onClick={() => setResultOpen((o) => !o)}
            className="w-full flex items-center justify-between gap-3 px-4 sm:px-5 py-4 hover:bg-gray-50 transition-colors rounded-2xl"
          >
            <div className="flex items-center gap-2 min-w-0 flex-1 flex-wrap">
              <Info className="w-4 h-4 text-gray-400 shrink-0" />
              <span className="text-sm font-black text-gray-700">Last Generation Result</span>
              {seed.completed_at && (
                <span className="text-xs text-gray-400 flex items-center gap-1 shrink-0">
                  <Clock className="w-3 h-3" />
                  {new Date(seed.completed_at).toLocaleTimeString()}
                </span>
              )}
            </div>
            {resultOpen ? <ChevronUp className="w-4 h-4 text-gray-400 shrink-0" /> : <ChevronDown className="w-4 h-4 text-gray-400 shrink-0" />}
          </button>
          {resultOpen && (
            <div className="px-5 pb-5">
              <pre className="text-xs text-gray-600 bg-gray-50 rounded-xl p-3 overflow-auto max-h-60 font-mono">
                {JSON.stringify(seed.last_result, null, 2)}
              </pre>
            </div>
          )}
        </div>
      )}

      {/* ── Image Source Settings ── */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
        <div className="flex items-center gap-2 mb-4">
          <div className="w-9 h-9 rounded-xl bg-violet-50 flex items-center justify-center">
            <Settings className="w-4 h-4 text-violet-600" />
          </div>
          <div>
            <p className="text-sm font-black text-gray-800">AI Generator Settings</p>
            <p className="text-xs text-gray-400">Real car images fetched automatically after generation</p>
          </div>
        </div>

        <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Image Source</p>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-2">
          {([
            { id: "google" as CarImageSource, label: "Google Custom Search", hint: "GOOGLE_CSE_API_KEY + CX" },
            { id: "serpapi" as CarImageSource, label: "SerpAPI", hint: "SERPAPI_API_KEY" },
            { id: "bing" as CarImageSource, label: "Bing Image Search", hint: "BING_IMAGE_SEARCH_API_KEY" },
            { id: "manual" as CarImageSource, label: "Manual Only", hint: "Admin upload fallback" },
          ]).map((opt) => {
            const configured = opt.id === "manual" || imgProviders?.[opt.id];
            const selected = imgSource === opt.id;
            return (
              <button
                key={opt.id}
                type="button"
                disabled={imgSaving}
                onClick={() => saveImageSource(opt.id)}
                className={cn(
                  "text-left p-3 rounded-xl border-2 transition-all",
                  selected
                    ? "border-violet-500 bg-violet-50"
                    : "border-gray-100 hover:border-violet-200 bg-white",
                  imgSaving && "opacity-60 cursor-not-allowed",
                )}
              >
                <div className="flex items-center gap-2">
                  <span className={cn(
                    "w-3.5 h-3.5 rounded-full border-2 shrink-0",
                    selected ? "border-violet-600 bg-violet-600" : "border-gray-300",
                  )} />
                  <span className="text-xs font-black text-gray-800">{opt.label}</span>
                </div>
                <p className="text-[10px] text-gray-400 mt-1 ml-5 break-words">{opt.hint}</p>
                {opt.id !== "manual" && (
                  <p className={cn(
                    "text-[10px] font-bold mt-1 ml-5",
                    configured ? "text-green-600" : "text-amber-600",
                  )}>
                    {configured ? "API key configured" : "Not configured"}
                  </p>
                )}
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-gray-400 mt-3 flex items-center gap-1">
          <ImageIcon className="w-3 h-3" />
          Downloads 1 hero + 4 gallery images per car, stores in media library as WebP.
        </p>
      </div>

      {/* ── Info box ── */}
      <div className="bg-blue-50 border border-blue-100 rounded-2xl p-4 flex gap-3">
        <Info className="w-4 h-4 text-blue-400 shrink-0 mt-0.5" />
        <div className="text-xs text-blue-700 space-y-1">
          <p className="font-bold">AI Provider Cascade: OpenAI → Gemini → Claude</p>
          <p>Uses your configured API keys. Falls back automatically on quota errors.</p>
          <p>Catalog contains <strong>{cat?.catalog_size ?? 0}</strong> cars across <strong>{cat?.available_brands?.length ?? 0}</strong> brands.</p>
          <p>All operations are idempotent — safe to run multiple times (upsert by slug).</p>
        </div>
      </div>
    </div>
  );
}
