import { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, Link } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import {
  Wrench, LogOut, Package, Users, DollarSign, TrendingUp,
  Clock, CheckCircle2, AlertCircle, Loader2, Trash2, Eye,
  FileText, Truck, Receipt, Plus, Send, LayoutGrid, X,
  ArrowRight, ChevronRight, Mail, Phone, Car, CreditCard,
  GripVertical, User, Globe, ExternalLink, StickyNote, Search
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from "@/components/ui/select";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow
} from "@/components/ui/table";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const STATUS_COLORS = {
  new: "bg-blue-900/50 text-blue-300 border-blue-800",
  in_progress: "bg-yellow-900/50 text-yellow-300 border-yellow-800",
  quoted: "bg-purple-900/50 text-purple-300 border-purple-800",
  completed: "bg-green-900/50 text-green-300 border-green-800",
  cancelled: "bg-red-900/50 text-red-300 border-red-800",
};

const PIPELINE_STAGES = [
  { key: "new_lead", label: "New Lead", color: "bg-blue-500" },
  { key: "vin_review", label: "VIN Review", color: "bg-indigo-500" },
  { key: "sourcing", label: "Sourcing", color: "bg-cyan-500" },
  { key: "quote_sent", label: "Quote Sent", color: "bg-purple-500" },
  { key: "invoice_sent", label: "Invoice Sent", color: "bg-amber-500" },
  { key: "paid", label: "Paid", color: "bg-emerald-500" },
  { key: "ordered", label: "Ordered", color: "bg-orange-500" },
  { key: "shipped", label: "Shipped", color: "bg-teal-500" },
  { key: "delivered", label: "Delivered", color: "bg-green-600" },
];

const NAV_ITEMS = [
  { key: "overview", label: "Overview", icon: LayoutGrid },
  { key: "pipeline", label: "Pipeline", icon: TrendingUp },
  { key: "customers", label: "Customers", icon: Users },
  { key: "sourcing", label: "Sourcing Hub", icon: Globe },
  { key: "requests", label: "Requests", icon: FileText },
  { key: "orders", label: "Orders", icon: Package },
  { key: "invoices", label: "Invoices", icon: Receipt },
  { key: "shipments", label: "Shipments", icon: Truck },
  { key: "contacts", label: "Leads", icon: Mail },
];

export default function AdminDashboard() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState("overview");
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [loading, setLoading] = useState(true);

  // Data
  const [stats, setStats] = useState(null);
  const [requests, setRequests] = useState([]);
  const [contacts, setContacts] = useState([]);
  const [quotes, setQuotes] = useState([]);
  const [orders, setOrders] = useState([]);
  const [invoices, setInvoices] = useState([]);
  const [shipments, setShipments] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [pipelineData, setPipelineData] = useState({});
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [customerProfile, setCustomerProfile] = useState(null);
  const [customerLoading, setCustomerLoading] = useState(false);
  const [sourcingNotes, setSourcingNotes] = useState([]);
  const [noteForm, setNoteForm] = useState({ title: "", content: "", category: "general", source_url: "" });
  const [noteFormOpen, setNoteFormOpen] = useState(false);

  // Dialogs
  const [selectedRequest, setSelectedRequest] = useState(null);
  const [editPricing, setEditPricing] = useState({ quoted_price: "", cost_price: "" });
  const [quoteDialog, setQuoteDialog] = useState(null);
  const [quoteForm, setQuoteForm] = useState({ total: "", notes: "", estimated_shipping: "", items: [{ description: "", quantity: 1, unit_price: "" }] });
  const [shipmentDialog, setShipmentDialog] = useState(null);
  const [shipmentForm, setShipmentForm] = useState({ carrier: "", tracking_number: "", estimated_delivery: "" });
  const [invoiceDialog, setInvoiceDialog] = useState(null);
  const [invoiceForm, setInvoiceForm] = useState({ amount: "", notes: "", due_date: "" });

  const token = localStorage.getItem("admin_token");
  const headers = useMemo(() => ({ Authorization: `Bearer ${token}` }), [token]);

  const loadData = useCallback(async () => {
    try {
      const [statsRes, reqsRes, contactsRes, quotesRes, ordersRes, invoicesRes, shipmentsRes, custRes, pipeRes, notesRes] = await Promise.all([
        axios.get(`${API}/dashboard/stats`, { headers }),
        axios.get(`${API}/part-requests`, { headers }),
        axios.get(`${API}/contacts`, { headers }),
        axios.get(`${API}/quotes`, { headers }),
        axios.get(`${API}/orders`, { headers }),
        axios.get(`${API}/invoices`, { headers }),
        axios.get(`${API}/shipments`, { headers }),
        axios.get(`${API}/admin/customers`, { headers }),
        axios.get(`${API}/admin/pipeline`, { headers }),
        axios.get(`${API}/admin/sourcing-notes`, { headers }),
      ]);
      setStats(statsRes.data);
      setRequests(reqsRes.data);
      setContacts(contactsRes.data);
      setQuotes(quotesRes.data);
      setOrders(ordersRes.data);
      setInvoices(invoicesRes.data);
      setShipments(shipmentsRes.data);
      setCustomers(custRes.data);
      setPipelineData(pipeRes.data);
      setSourcingNotes(notesRes.data);
    } catch {
      toast.error("Session expired. Please login again.");
      localStorage.removeItem("admin_token");
      navigate("/admin/login");
    }
    setLoading(false);
  }, [headers, navigate]);

  useEffect(() => {
    if (!token) { navigate("/admin/login"); return; }
    loadData();
  }, [token, navigate, loadData]);

  const loadCustomerProfile = async (customerId) => {
    setCustomerLoading(true);
    try {
      const { data } = await axios.get(`${API}/admin/customers/${customerId}`, { headers });
      setCustomerProfile(data);
    } catch { toast.error("Failed to load customer profile"); }
    setCustomerLoading(false);
  };

  // --- Handlers ---
  const handleStatusChange = async (id, status) => {
    try {
      await axios.patch(`${API}/part-requests/${id}`, { status }, { headers });
      toast.success("Status updated");
      loadData();
    } catch { toast.error("Failed to update status"); }
  };

  const handlePricingUpdate = async (id) => {
    const data = {};
    if (editPricing.quoted_price) data.quoted_price = parseFloat(editPricing.quoted_price);
    if (editPricing.cost_price) data.cost_price = parseFloat(editPricing.cost_price);
    try {
      await axios.patch(`${API}/part-requests/${id}`, data, { headers });
      toast.success("Pricing updated");
      setSelectedRequest(null);
      loadData();
    } catch { toast.error("Failed to update pricing"); }
  };

  const handleDeleteRequest = async (id) => {
    try {
      await axios.delete(`${API}/part-requests/${id}`, { headers });
      toast.success("Request deleted");
      loadData();
    } catch { toast.error("Failed to delete"); }
  };

  const handleCreateQuote = async () => {
    if (!quoteForm.total) { toast.error("Enter a total price"); return; }
    try {
      await axios.post(`${API}/quotes`, { request_id: quoteDialog.id, items: quoteForm.items.filter(i => i.description), total: parseFloat(quoteForm.total), notes: quoteForm.notes, estimated_shipping: quoteForm.estimated_shipping }, { headers });
      toast.success("Quote sent!");
      setQuoteDialog(null);
      setQuoteForm({ total: "", notes: "", estimated_shipping: "", items: [{ description: "", quantity: 1, unit_price: "" }] });
      loadData();
    } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
  };

  const handleUpdateOrderStatus = async (orderId, status) => {
    try {
      await axios.patch(`${API}/orders/${orderId}`, { status }, { headers });
      toast.success("Order updated");
      loadData();
    } catch { toast.error("Failed"); }
  };

  const handleCreateInvoice = async () => {
    if (!invoiceForm.amount) { toast.error("Enter an amount"); return; }
    try {
      await axios.post(`${API}/invoices`, { order_id: invoiceDialog.id, amount: parseFloat(invoiceForm.amount), notes: invoiceForm.notes, due_date: invoiceForm.due_date }, { headers });
      toast.success("Invoice created!");
      setInvoiceDialog(null);
      setInvoiceForm({ amount: "", notes: "", due_date: "" });
      loadData();
    } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
  };

  const handleMarkInvoicePaid = async (invoiceId) => {
    try {
      await axios.patch(`${API}/invoices/${invoiceId}/pay`, {}, { headers });
      toast.success("Invoice marked as paid");
      loadData();
    } catch { toast.error("Failed"); }
  };

  const handleCreateShipment = async () => {
    if (!shipmentForm.carrier || !shipmentForm.tracking_number) { toast.error("Enter carrier and tracking"); return; }
    try {
      await axios.post(`${API}/shipments`, { order_id: shipmentDialog.id, ...shipmentForm }, { headers });
      toast.success("Shipment created!");
      setShipmentDialog(null);
      setShipmentForm({ carrier: "", tracking_number: "", estimated_delivery: "" });
      loadData();
    } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
  };

  const handleMarkDelivered = async (shipmentId) => {
    try {
      await axios.patch(`${API}/shipments/${shipmentId}/deliver`, {}, { headers });
      toast.success("Marked as delivered");
      loadData();
    } catch { toast.error("Failed"); }
  };

  const handlePipelineMove = async (requestId, newStage) => {
    try {
      await axios.patch(`${API}/admin/pipeline/${requestId}`, { pipeline_stage: newStage }, { headers });
      toast.success(`Moved to ${PIPELINE_STAGES.find(s => s.key === newStage)?.label}`);
      loadData();
    } catch { toast.error("Failed to move"); }
  };

  const handleCreateNote = async (e) => {
    e.preventDefault();
    if (!noteForm.title || !noteForm.content) { toast.error("Title and content required"); return; }
    try {
      await axios.post(`${API}/admin/sourcing-notes`, noteForm, { headers });
      toast.success("Note saved!");
      setNoteForm({ title: "", content: "", category: "general", source_url: "" });
      setNoteFormOpen(false);
      loadData();
    } catch { toast.error("Failed to save note"); }
  };

  const handleDeleteNote = async (id) => {
    try {
      await axios.delete(`${API}/admin/sourcing-notes/${id}`, { headers });
      toast.success("Note deleted");
      loadData();
    } catch { toast.error("Failed to delete"); }
  };

  const logout = () => {
    localStorage.removeItem("admin_token");
    localStorage.removeItem("admin_username");
    navigate("/admin/login");
  };

  const inputCls = "bg-[#1E1E1E] border-#2A2A2A focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]/50 rounded-none h-10 text-white text-sm";

  if (loading) return <div className="min-h-screen bg-[#0B0B0B] flex items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-[#3B82F6]" /></div>;

  return (
    <div data-testid="admin-dashboard" className="min-h-screen bg-[#0B0B0B] flex">
      {/* SIDEBAR */}
      <aside className={`fixed inset-y-0 left-0 z-40 w-56 bg-[#0B0B0B] border-r border-#2A2A2A transform transition-transform duration-200 lg:relative lg:translate-x-0 ${sidebarOpen ? "translate-x-0" : "-translate-x-full"}`}>
        <div className="p-4 border-b border-#2A2A2A">
          <Link to="/" className="flex items-center gap-2">
            <Wrench className="h-5 w-5 text-[#3B82F6]" />
            <span className="font-bold text-base uppercase tracking-[0.08em] font-['Inter'] text-white">
              Admin <span className="text-[#3B82F6]">CRM</span>
            </span>
          </Link>
        </div>
        <nav className="p-2 space-y-0.5">
          {NAV_ITEMS.map(item => (
            <button
              key={item.key}
              data-testid={`admin-nav-${item.key}`}
              onClick={() => { setActiveTab(item.key); setSidebarOpen(false); setSelectedCustomer(null); }}
              className={`w-full flex items-center gap-2.5 px-3 py-2 text-[11px] uppercase tracking-[0.08em] font-medium transition-colors ${
                activeTab === item.key
                  ? "bg-[#3B82F6]/10 text-[#3B82F6] border-l-2 border-[#3B82F6]"
                  : "text-[#666] hover:text-white hover:bg-white/[0.03] border-l-2 border-transparent"
              }`}
            >
              <item.icon className="h-3.5 w-3.5" />
              {item.label}
            </button>
          ))}
        </nav>
        <div className="absolute bottom-0 left-0 right-0 p-3 border-t border-#2A2A2A">
          <Button data-testid="admin-logout-btn" onClick={logout} variant="ghost" className="w-full justify-start text-[#555] hover:text-white rounded-none text-[10px] uppercase tracking-[0.08em] h-8 px-2">
            <LogOut className="h-3.5 w-3.5 mr-2" /> Sign Out
          </Button>
        </div>
      </aside>

      {/* MOBILE HEADER */}
      <div className="lg:hidden fixed top-0 left-0 right-0 z-30 bg-[#0B0B0B] border-b border-#2A2A2A px-4 py-3 flex items-center justify-between">
        <button onClick={() => setSidebarOpen(!sidebarOpen)} className="text-white p-1">
          {sidebarOpen ? <X className="h-5 w-5" /> : <LayoutGrid className="h-5 w-5" />}
        </button>
        <span className="font-semibold text-sm uppercase tracking-[0.1em] font-['Inter'] text-white">Admin CRM</span>
        <Button onClick={logout} variant="ghost" className="text-[#666] h-8 w-8 p-0"><LogOut className="h-4 w-4" /></Button>
      </div>
      {sidebarOpen && <div className="lg:hidden fixed inset-0 z-30 bg-black/50" onClick={() => setSidebarOpen(false)} />}

      {/* MAIN */}
      <main className="flex-1 min-h-screen pt-14 lg:pt-0 overflow-x-hidden">
        <div className="p-5 lg:p-6">

          {/* ============ OVERVIEW ============ */}
          {activeTab === "overview" && stats && (
            <div className="space-y-6">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Dashboard Overview</h1>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {[
                  { label: "Total Requests", value: stats.total_requests, icon: FileText, accent: "text-blue-400" },
                  { label: "Customers", value: stats.total_customers, icon: Users, accent: "text-cyan-400" },
                  { label: "Active Orders", value: stats.total_orders, icon: Package, accent: "text-amber-400" },
                  { label: "Total Collected", value: `$${(stats.total_collected || 0).toLocaleString()}`, icon: CreditCard, accent: "text-emerald-400" },
                ].map(s => (
                  <div key={s.label} className="bg-[#121212] border border-#2A2A2A p-5">
                    <s.icon className={`h-4 w-4 ${s.accent} mb-3`} />
                    <p className="text-3xl font-semibold font-['Inter'] text-white leading-none">{s.value}</p>
                    <p className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mt-1">{s.label}</p>
                  </div>
                ))}
              </div>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {[
                  { label: "Quotes Sent", value: stats.total_quotes, icon: Send, accent: "text-purple-400" },
                  { label: "Unpaid Invoices", value: stats.unpaid_invoices, icon: AlertCircle, accent: "text-[#3B82F6]" },
                  { label: "Paid Invoices", value: stats.paid_invoices, icon: CheckCircle2, accent: "text-emerald-400" },
                  { label: "Total Profit", value: `$${(stats.total_profit || 0).toLocaleString()}`, icon: TrendingUp, accent: "text-green-400" },
                ].map(s => (
                  <div key={s.label} className="bg-[#121212] border border-#2A2A2A p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-[#555]">{s.label}</p>
                      <s.icon className={`h-3.5 w-3.5 ${s.accent}`} />
                    </div>
                    <p className="text-xl font-semibold font-['Inter'] text-white">{s.value}</p>
                  </div>
                ))}
              </div>
              {/* Quick nav */}
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {[
                  { label: "View Pipeline", icon: TrendingUp, action: () => setActiveTab("pipeline") },
                  { label: "Manage Customers", icon: Users, action: () => setActiveTab("customers") },
                  { label: "View Orders", icon: Package, action: () => setActiveTab("orders") },
                  { label: "View Invoices", icon: Receipt, action: () => setActiveTab("invoices") },
                ].map(a => (
                  <button key={a.label} onClick={a.action} className="bg-[#121212] border border-#2A2A2A p-4 text-left hover:border-[#3B82F6]/30 transition-colors group">
                    <a.icon className="h-4 w-4 text-[#555] group-hover:text-[#3B82F6] mb-2 transition-colors" />
                    <p className="text-[11px] uppercase tracking-[0.08em] text-[#777] group-hover:text-white transition-colors font-medium">{a.label}</p>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* ============ PIPELINE ============ */}
          {activeTab === "pipeline" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Deal Pipeline</h1>
              <div className="overflow-x-auto pb-4">
                <div className="flex gap-3 min-w-[1200px]">
                  {PIPELINE_STAGES.map(stage => {
                    const items = pipelineData[stage.key] || [];
                    return (
                      <div key={stage.key} data-testid={`pipeline-stage-${stage.key}`} className="flex-1 min-w-[150px]">
                        <div className={`${stage.color} h-1 mb-2`} />
                        <div className="flex items-center justify-between mb-3">
                          <h3 className="text-[10px] font-bold uppercase tracking-[0.12em] text-[#888]">{stage.label}</h3>
                          <span className="text-[10px] font-semibold text-[#555] bg-[#1a1a1a] px-1.5 py-0.5">{items.length}</span>
                        </div>
                        <div className="space-y-2 min-h-[100px]">
                          {items.map(req => (
                            <div key={req.id} data-testid={`pipeline-card-${req.id}`} className="bg-[#121212] border border-#2A2A2A p-3 hover:border-#2A2A2A transition-colors group">
                              <p className="text-[11px] text-[#3B82F6] font-semibold mb-0.5">{req.vehicle_year} {req.make} {req.model}</p>
                              <p className="text-xs text-white font-medium mb-1 line-clamp-1">{req.part_needed}</p>
                              <p className="text-[10px] text-[#555] mb-2">{req.name}</p>
                              <Select value={stage.key} onValueChange={(v) => handlePipelineMove(req.id, v)}>
                                <SelectTrigger className="h-6 rounded-none text-[9px] uppercase tracking-wider border-#2A2A2A bg-[#1E1E1E] text-[#888]">
                                  <GripVertical className="h-3 w-3 mr-1 opacity-50" /><SelectValue />
                                </SelectTrigger>
                                <SelectContent className="bg-[#1E1E1E] border-white/10">
                                  {PIPELINE_STAGES.map(s => (
                                    <SelectItem key={s.key} value={s.key} className="text-[10px] uppercase">{s.label}</SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {/* ============ SOURCING HUB ============ */}
          {activeTab === "sourcing" && (
            <div className="space-y-6">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Sourcing Hub</h1>

              {/* FB Marketplace Quick Searches */}
              <div>
                <h2 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><Globe className="h-3.5 w-3.5" /> Facebook Marketplace — Charlotte, NC</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                  {[
                    { label: "Daily Part Outs", query: "parting out car", emoji: "🔧" },
                    { label: "Engine Part Outs", query: "parting out engine", emoji: "⚙️" },
                    { label: "Transmission Part Outs", query: "parting out transmission", emoji: "🔩" },
                    { label: "Body Parts / Panels", query: "car body parts", emoji: "🚗" },
                    { label: "OEM Parts Cheap", query: "OEM auto parts", emoji: "📦" },
                    { label: "Salvage / Junk Cars", query: "salvage car parts", emoji: "🏗️" },
                    { label: "Headlights & Taillights", query: "headlight taillight assembly", emoji: "💡" },
                    { label: "Wheels & Tires", query: "wheels tires OEM", emoji: "🛞" },
                    { label: "Interior Parts", query: "car interior parts seats", emoji: "💺" },
                  ].map(s => (
                    <a
                      key={s.label}
                      href={`https://www.facebook.com/marketplace/charlotte/search?query=${encodeURIComponent(s.query)}&exact=false`}
                      target="_blank"
                      rel="noopener noreferrer"
                      data-testid={`fb-search-${s.label.toLowerCase().replace(/\s+/g, "-")}`}
                      className="bg-[#121212] border border-#2A2A2A p-4 hover:border-[#1877F2]/40 transition-colors group flex items-center justify-between"
                    >
                      <div className="flex items-center gap-3">
                        <span className="text-lg">{s.emoji}</span>
                        <div>
                          <p className="text-sm text-white font-medium group-hover:text-[#1877F2] transition-colors">{s.label}</p>
                          <p className="text-[10px] text-[#555]">Charlotte area</p>
                        </div>
                      </div>
                      <ExternalLink className="h-3.5 w-3.5 text-[#444] group-hover:text-[#1877F2] transition-colors" />
                    </a>
                  ))}
                </div>
              </div>

              {/* Junkyard / Salvage Directory */}
              <div>
                <h2 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><Search className="h-3.5 w-3.5" /> Junkyard & Salvage Yard Directory</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {[
                    { name: "Pull-A-Part Charlotte", url: "https://www.pullapart.com/locations/charlotte-nc/", type: "Self-Service Yard", phone: "(704) 392-3800", desc: "Self-service yard, great for common parts. Check online inventory first." },
                    { name: "LKQ Pick Your Part", url: "https://www.lkqpickyourpart.com/", type: "Self-Service Yard", phone: "", desc: "Nationwide chain. Search inventory online by vehicle. Frequent inventory updates." },
                    { name: "LKQ Online (Wholesale)", url: "https://www.lkqonline.com/", type: "Wholesale Supplier", phone: "", desc: "Wholesale recycled OEM parts. Search by part number or vehicle. Delivery available." },
                    { name: "Car-Part.com", url: "https://www.car-part.com/", type: "Inventory Aggregator", phone: "", desc: "Searches 200+ salvage yards nationwide. Best for finding specific parts fast." },
                    { name: "Row52", url: "https://row52.com/", type: "Yard Inventory Search", phone: "", desc: "Free inventory search across self-service yards. Set alerts for specific vehicles." },
                    { name: "Copart (Auctions)", url: "https://www.copart.com/", type: "Salvage Auction", phone: "", desc: "Salvage vehicle auctions. Buy whole vehicles to part out. Requires dealer license for some." },
                    { name: "IAAI (Auctions)", url: "https://www.iaai.com/", type: "Salvage Auction", phone: "", desc: "Insurance Auto Auctions. Another major salvage auction source. Good for specialty vehicles." },
                    { name: "eBay Motors Parts", url: "https://www.ebay.com/b/Auto-Parts-and-Accessories/6028/bn_559860", type: "Marketplace", phone: "", desc: "Used & new OEM parts from sellers nationwide. Check seller ratings and fitment." },
                  ].map(yard => (
                    <a
                      key={yard.name}
                      href={yard.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      data-testid={`yard-${yard.name.toLowerCase().replace(/\s+/g, "-")}`}
                      className="bg-[#121212] border border-#2A2A2A p-5 hover:border-[#3B82F6]/30 transition-colors group"
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <p className="text-sm text-white font-semibold group-hover:text-[#3B82F6] transition-colors">{yard.name}</p>
                          <Badge className="rounded-none text-[8px] uppercase border bg-white/[0.04] text-[#888] border-#2A2A2A mt-1">{yard.type}</Badge>
                        </div>
                        <ExternalLink className="h-3.5 w-3.5 text-[#444] group-hover:text-[#3B82F6] transition-colors flex-shrink-0 mt-1" />
                      </div>
                      <p className="text-[11px] text-[#666] mt-2 leading-relaxed">{yard.desc}</p>
                      {yard.phone && <p className="text-[11px] text-[#555] mt-2 flex items-center gap-1"><Phone className="h-3 w-3" />{yard.phone}</p>}
                    </a>
                  ))}
                </div>
              </div>

              {/* Sourcing Notes */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h2 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] flex items-center gap-2"><StickyNote className="h-3.5 w-3.5" /> Sourcing Notes & Leads</h2>
                  <Button data-testid="add-sourcing-note" onClick={() => setNoteFormOpen(!noteFormOpen)} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[10px] h-8 px-4">
                    <Plus className="h-3 w-3 mr-1" /> Add Note
                  </Button>
                </div>

                {noteFormOpen && (
                  <form onSubmit={handleCreateNote} data-testid="note-form" className="bg-[#121212] border border-[#3B82F6]/20 p-5 mb-4 space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div><Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Title *</Label><Input data-testid="note-title" placeholder="e.g. 2018 Camry partout on FB" value={noteForm.title} onChange={e => setNoteForm({...noteForm, title: e.target.value})} className={inputCls} required /></div>
                      <div>
                        <Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Category</Label>
                        <Select value={noteForm.category} onValueChange={v => setNoteForm({...noteForm, category: v})}>
                          <SelectTrigger className={`${inputCls} w-full`}><SelectValue /></SelectTrigger>
                          <SelectContent className="bg-[#1E1E1E] border-white/10">
                            <SelectItem value="general">General</SelectItem>
                            <SelectItem value="partout">Part Out</SelectItem>
                            <SelectItem value="junkyard">Junkyard</SelectItem>
                            <SelectItem value="auction">Auction</SelectItem>
                            <SelectItem value="wholesale">Wholesale</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <div><Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Source URL</Label><Input data-testid="note-url" placeholder="https://facebook.com/marketplace/..." value={noteForm.source_url} onChange={e => setNoteForm({...noteForm, source_url: e.target.value})} className={inputCls} /></div>
                    <div><Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Details *</Label><textarea data-testid="note-content" placeholder="What's available, pricing, contact info..." value={noteForm.content} onChange={e => setNoteForm({...noteForm, content: e.target.value})} rows={3} className="bg-[#1E1E1E] border border-#2A2A2A rounded-none w-full p-3 text-white text-sm resize-none outline-none focus:border-[#3B82F6] placeholder:text-[#444]" required /></div>
                    <div className="flex gap-2">
                      <Button data-testid="save-note-btn" type="submit" className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-9 px-5">Save Note</Button>
                      <Button type="button" variant="ghost" onClick={() => setNoteFormOpen(false)} className="text-[#666] rounded-none text-[11px] h-9 uppercase">Cancel</Button>
                    </div>
                  </form>
                )}

                <div className="space-y-2">
                  {sourcingNotes.map(note => {
                    const catColors = { partout: "text-blue-400 bg-blue-900/30 border-blue-800/40", junkyard: "text-amber-400 bg-amber-900/30 border-amber-800/40", auction: "text-purple-400 bg-purple-900/30 border-purple-800/40", wholesale: "text-cyan-400 bg-cyan-900/30 border-cyan-800/40", general: "text-[#888] bg-white/[0.04] border-#2A2A2A" };
                    return (
                      <div key={note.id} data-testid={`sourcing-note-${note.id}`} className="bg-[#121212] border border-#2A2A2A p-4">
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-1.5">
                              <p className="text-sm text-white font-medium">{note.title}</p>
                              <Badge className={`rounded-none text-[8px] uppercase border ${catColors[note.category] || catColors.general}`}>{note.category}</Badge>
                            </div>
                            <p className="text-[12px] text-[#888] leading-relaxed whitespace-pre-wrap">{note.content}</p>
                            <div className="flex items-center gap-4 mt-2">
                              {note.source_url && <a href={note.source_url} target="_blank" rel="noopener noreferrer" className="text-[10px] text-[#3B82F6] hover:underline flex items-center gap-1"><ExternalLink className="h-3 w-3" />View Source</a>}
                              <span className="text-[10px] text-[#444]">{new Date(note.created_at).toLocaleDateString()}</span>
                            </div>
                          </div>
                          <button data-testid={`delete-note-${note.id}`} onClick={() => handleDeleteNote(note.id)} className="text-[#444] hover:text-red-400 p-1 transition-colors flex-shrink-0 ml-3"><Trash2 className="h-3.5 w-3.5" /></button>
                        </div>
                      </div>
                    );
                  })}
                  {sourcingNotes.length === 0 && !noteFormOpen && (
                    <div className="bg-[#121212] border border-#2A2A2A p-12 text-center">
                      <StickyNote className="h-8 w-8 text-[#333] mx-auto mb-3" />
                      <p className="text-[#555] text-sm mb-3">No sourcing notes yet. Track marketplace finds and junkyard leads here.</p>
                      <Button onClick={() => setNoteFormOpen(true)} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[10px] h-8 px-4">
                        <Plus className="h-3 w-3 mr-1" /> Add First Note
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* ============ CUSTOMERS ============ */}
          {activeTab === "customers" && !selectedCustomer && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Customers</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Customer</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Email</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Requests</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Orders</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Total Billed</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Outstanding</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Joined</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]"></TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {customers.map(c => (
                      <TableRow key={c.id} data-testid={`customer-row-${c.id}`} className="border-#2A2A2A hover:bg-white/[0.02] cursor-pointer" onClick={() => { setSelectedCustomer(c.id); loadCustomerProfile(c.id); }}>
                        <TableCell><p className="text-sm text-white font-medium">{c.name}</p></TableCell>
                        <TableCell className="text-sm text-[#888]">{c.email}</TableCell>
                        <TableCell className="text-sm text-white">{c.requests_count}</TableCell>
                        <TableCell className="text-sm text-white">{c.orders_count}</TableCell>
                        <TableCell className="text-sm text-white font-semibold">${(c.invoices_total || 0).toLocaleString()}</TableCell>
                        <TableCell>
                          {c.unpaid_amount > 0 ? <span className="text-sm font-semibold text-[#3B82F6]">${c.unpaid_amount.toLocaleString()}</span> : <span className="text-[11px] text-[#555]">$0</span>}
                        </TableCell>
                        <TableCell className="text-[11px] text-[#555]">{new Date(c.created_at).toLocaleDateString()}</TableCell>
                        <TableCell><ChevronRight className="h-4 w-4 text-[#444]" /></TableCell>
                      </TableRow>
                    ))}
                    {customers.length === 0 && <TableRow><TableCell colSpan={8} className="text-center py-8 text-[#555]">No customers yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* CUSTOMER PROFILE */}
          {activeTab === "customers" && selectedCustomer && (
            <div className="space-y-6">
              <div className="flex items-center gap-3">
                <button data-testid="back-to-customers" onClick={() => { setSelectedCustomer(null); setCustomerProfile(null); }} className="text-[#666] hover:text-white transition-colors">
                  <ArrowRight className="h-4 w-4 rotate-180" />
                </button>
                <h1 className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Customer Profile</h1>
              </div>
              {customerLoading ? <div className="flex justify-center py-20"><Loader2 className="h-6 w-6 animate-spin text-[#3B82F6]" /></div> : customerProfile && (
                <div className="space-y-6">
                  {/* Profile header */}
                  <div data-testid="customer-profile-header" className="bg-[#121212] border border-#2A2A2A p-6">
                    <div className="flex items-start gap-4">
                      <div className="h-12 w-12 bg-[#3B82F6]/10 flex items-center justify-center flex-shrink-0">
                        <User className="h-6 w-6 text-[#3B82F6]" />
                      </div>
                      <div className="flex-1">
                        <h2 className="text-xl font-bold font-['Inter'] text-white uppercase">{customerProfile.name}</h2>
                        <div className="flex flex-wrap gap-4 mt-2 text-sm">
                          <span className="text-[#888] flex items-center gap-1.5"><Mail className="h-3.5 w-3.5" />{customerProfile.email}</span>
                          {customerProfile.phone && <span className="text-[#888] flex items-center gap-1.5"><Phone className="h-3.5 w-3.5" />{customerProfile.phone}</span>}
                        </div>
                        <p className="text-[11px] text-[#555] mt-2">Member since {new Date(customerProfile.created_at).toLocaleDateString()}</p>
                      </div>
                    </div>
                    {/* Stats */}
                    <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 mt-5">
                      {[
                        { label: "Vehicles", value: customerProfile.vehicles?.length || 0 },
                        { label: "Requests", value: customerProfile.requests?.length || 0 },
                        { label: "Orders", value: customerProfile.orders?.length || 0 },
                        { label: "Invoices", value: customerProfile.invoices?.length || 0 },
                        { label: "Payments", value: customerProfile.payments?.length || 0 },
                      ].map(s => (
                        <div key={s.label} className="bg-[#1E1E1E] p-3">
                          <p className="text-xl font-semibold font-['Inter'] text-white">{s.value}</p>
                          <p className="text-[9px] uppercase tracking-[0.12em] text-[#555]">{s.label}</p>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Vehicles */}
                  {customerProfile.vehicles?.length > 0 && (
                    <div>
                      <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><Car className="h-3.5 w-3.5" /> Vehicles ({customerProfile.vehicles.length})</h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        {customerProfile.vehicles.map(v => (
                          <div key={v.id} className="bg-[#121212] border border-#2A2A2A p-4">
                            <p className="text-white font-semibold">{v.year} {v.make} {v.model}</p>
                            {v.vin && <p className="text-[11px] text-[#555] font-mono mt-1">VIN: {v.vin}</p>}
                            {v.engine && <p className="text-[11px] text-[#555]">Engine: {v.engine}</p>}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Orders */}
                  {customerProfile.orders?.length > 0 && (
                    <div>
                      <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><Package className="h-3.5 w-3.5" /> Orders ({customerProfile.orders.length})</h3>
                      <div className="space-y-2">
                        {customerProfile.orders.map(o => (
                          <div key={o.id} className="bg-[#121212] border border-#2A2A2A p-4 flex items-center justify-between">
                            <div>
                              <p className="text-[10px] text-[#555] font-mono">{o.order_number}</p>
                              <p className="text-sm text-white">{o.part_needed}</p>
                              <p className="text-[11px] text-[#666]">{o.vehicle_info}</p>
                            </div>
                            <div className="text-right">
                              <p className="text-lg font-semibold font-['Inter'] text-white">${o.total?.toLocaleString()}</p>
                              <Badge className="rounded-none text-[9px] uppercase">{o.status}</Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Invoices */}
                  {customerProfile.invoices?.length > 0 && (
                    <div>
                      <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><Receipt className="h-3.5 w-3.5" /> Invoices ({customerProfile.invoices.length})</h3>
                      <div className="space-y-2">
                        {customerProfile.invoices.map(inv => (
                          <div key={inv.id} className="bg-[#121212] border border-#2A2A2A p-4 flex items-center justify-between">
                            <div>
                              <p className="text-[10px] text-[#555] font-mono">{inv.invoice_number}</p>
                              <p className="text-sm text-white">{inv.part_needed || inv.vehicle_info}</p>
                            </div>
                            <div className="text-right">
                              <p className="text-lg font-semibold font-['Inter'] text-white">${inv.amount?.toLocaleString()}</p>
                              <Badge className={`rounded-none text-[9px] uppercase border ${inv.status === "paid" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-amber-900/40 text-amber-300 border-amber-800/50"}`}>{inv.status}</Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Payments */}
                  {customerProfile.payments?.length > 0 && (
                    <div>
                      <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888] mb-3 flex items-center gap-2"><CreditCard className="h-3.5 w-3.5" /> Payments ({customerProfile.payments.length})</h3>
                      <div className="space-y-2">
                        {customerProfile.payments.map(p => (
                          <div key={p.id} className="bg-[#121212] border border-#2A2A2A p-4 flex items-center justify-between">
                            <div>
                              <p className="text-[10px] text-[#555] font-mono">{p.session_id?.slice(0, 20)}...</p>
                              <p className="text-[11px] text-[#666]">{new Date(p.created_at).toLocaleDateString()}</p>
                            </div>
                            <div className="text-right">
                              <p className="text-lg font-semibold font-['Inter'] text-white">${p.amount?.toLocaleString()}</p>
                              <Badge className={`rounded-none text-[9px] uppercase border ${p.payment_status === "paid" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-amber-900/40 text-amber-300 border-amber-800/50"}`}>{p.payment_status}</Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {/* ============ REQUESTS ============ */}
          {activeTab === "requests" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Part Requests</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Customer</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Vehicle</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Part</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Status</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Profit</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Date</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Actions</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {requests.map(req => (
                      <TableRow key={req.id} data-testid={`request-row-${req.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                        <TableCell><p className="text-sm text-white font-medium">{req.name}</p><p className="text-[11px] text-[#555]">{req.email}</p></TableCell>
                        <TableCell className="text-sm text-[#888]">{req.vehicle_year} {req.make} {req.model}</TableCell>
                        <TableCell className="text-sm text-white">{req.part_needed}</TableCell>
                        <TableCell>
                          <Select value={req.status} onValueChange={v => handleStatusChange(req.id, v)}>
                            <SelectTrigger className={`w-[120px] h-7 rounded-none border text-[10px] uppercase ${STATUS_COLORS[req.status] || ""}`}><SelectValue /></SelectTrigger>
                            <SelectContent className="bg-neutral-900 border-white/10">
                              {["new","in_progress","quoted","completed","cancelled"].map(s => <SelectItem key={s} value={s}>{s.replace("_"," ")}</SelectItem>)}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell>{req.profit != null ? <span className={`text-sm font-semibold ${req.profit > 0 ? "text-green-400" : "text-red-400"}`}>${req.profit.toLocaleString()}</span> : <span className="text-[11px] text-[#555]">--</span>}</TableCell>
                        <TableCell className="text-[11px] text-[#555]">{new Date(req.created_at).toLocaleDateString()}</TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            <Button data-testid={`view-request-${req.id}`} variant="ghost" size="sm" onClick={() => { setSelectedRequest(req); setEditPricing({ quoted_price: req.quoted_price || "", cost_price: req.cost_price || "" }); }} className="h-7 w-7 p-0 text-[#555] hover:text-white"><Eye className="h-3.5 w-3.5" /></Button>
                            <Button data-testid={`send-quote-${req.id}`} variant="ghost" size="sm" onClick={() => { setQuoteDialog(req); setQuoteForm({ total: "", notes: "", estimated_shipping: "", items: [{ description: req.part_needed, quantity: 1, unit_price: "" }] }); }} className="h-7 w-7 p-0 text-[#555] hover:text-purple-400"><Send className="h-3.5 w-3.5" /></Button>
                            <Button data-testid={`delete-request-${req.id}`} variant="ghost" size="sm" onClick={() => handleDeleteRequest(req.id)} className="h-7 w-7 p-0 text-[#555] hover:text-red-400"><Trash2 className="h-3.5 w-3.5" /></Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                    {requests.length === 0 && <TableRow><TableCell colSpan={7} className="text-center py-8 text-[#555]">No requests yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* ============ ORDERS ============ */}
          {activeTab === "orders" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Orders</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Order #</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Vehicle / Part</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Total</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Status</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Date</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Actions</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {orders.map(o => (
                      <TableRow key={o.id} data-testid={`order-row-${o.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                        <TableCell className="text-sm text-white font-mono">{o.order_number}</TableCell>
                        <TableCell><p className="text-[11px] text-[#3B82F6]">{o.vehicle_info}</p><p className="text-sm text-white">{o.part_needed}</p></TableCell>
                        <TableCell className="text-sm text-white font-semibold">${o.total?.toLocaleString()}</TableCell>
                        <TableCell>
                          <Select value={o.status} onValueChange={v => handleUpdateOrderStatus(o.id, v)}>
                            <SelectTrigger className="w-[120px] h-7 rounded-none border text-[10px] uppercase"><SelectValue /></SelectTrigger>
                            <SelectContent className="bg-neutral-900 border-white/10">
                              {["processing","shipped","delivered"].map(s => <SelectItem key={s} value={s}>{s}</SelectItem>)}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell className="text-[11px] text-[#555]">{new Date(o.created_at).toLocaleDateString()}</TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            <Button data-testid={`add-shipment-${o.id}`} variant="ghost" size="sm" onClick={() => { setShipmentDialog(o); setShipmentForm({ carrier: "", tracking_number: "", estimated_delivery: "" }); }} className="h-7 px-2 text-[10px] text-[#555] hover:text-cyan-400 uppercase"><Truck className="h-3.5 w-3.5 mr-1" />Ship</Button>
                            <Button data-testid={`add-invoice-${o.id}`} variant="ghost" size="sm" onClick={() => { setInvoiceDialog(o); setInvoiceForm({ amount: o.total || "", notes: "", due_date: "" }); }} className="h-7 px-2 text-[10px] text-[#555] hover:text-amber-400 uppercase"><Receipt className="h-3.5 w-3.5 mr-1" />Invoice</Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                    {orders.length === 0 && <TableRow><TableCell colSpan={6} className="text-center py-8 text-[#555]">No orders yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* ============ INVOICES ============ */}
          {activeTab === "invoices" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Invoices</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Invoice #</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Order #</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Part</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Amount</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Status</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Date</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Actions</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {invoices.map(inv => (
                      <TableRow key={inv.id} data-testid={`admin-invoice-${inv.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                        <TableCell className="text-sm text-white font-mono">{inv.invoice_number}</TableCell>
                        <TableCell className="text-sm text-[#888] font-mono">{inv.order_number || "--"}</TableCell>
                        <TableCell className="text-sm text-[#888]">{inv.part_needed || inv.vehicle_info}</TableCell>
                        <TableCell className="text-sm text-white font-semibold">${inv.amount?.toLocaleString()}</TableCell>
                        <TableCell><Badge className={`rounded-none text-[10px] uppercase border ${inv.status === "paid" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-amber-900/40 text-amber-300 border-amber-800/50"}`}>{inv.status}</Badge></TableCell>
                        <TableCell className="text-[11px] text-[#555]">{new Date(inv.created_at).toLocaleDateString()}</TableCell>
                        <TableCell>{inv.status !== "paid" && <Button data-testid={`mark-paid-${inv.id}`} variant="ghost" size="sm" onClick={() => handleMarkInvoicePaid(inv.id)} className="h-7 px-2 text-[10px] text-[#555] hover:text-green-400 uppercase"><CheckCircle2 className="h-3.5 w-3.5 mr-1" />Mark Paid</Button>}</TableCell>
                      </TableRow>
                    ))}
                    {invoices.length === 0 && <TableRow><TableCell colSpan={7} className="text-center py-8 text-[#555]">No invoices yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* ============ SHIPMENTS ============ */}
          {activeTab === "shipments" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Shipments</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Order #</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Part</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Carrier</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Tracking #</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Est. Delivery</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Status</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Actions</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {shipments.map(sh => (
                      <TableRow key={sh.id} data-testid={`admin-shipment-${sh.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                        <TableCell className="text-sm text-white font-mono">{sh.order_number || "--"}</TableCell>
                        <TableCell className="text-sm text-[#888]">{sh.part_needed || sh.vehicle_info}</TableCell>
                        <TableCell className="text-sm text-white">{sh.carrier}</TableCell>
                        <TableCell className="text-sm text-white font-mono">{sh.tracking_number}</TableCell>
                        <TableCell className="text-sm text-[#888]">{sh.estimated_delivery || "--"}</TableCell>
                        <TableCell><Badge className={`rounded-none text-[10px] uppercase border ${sh.status === "delivered" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-cyan-900/40 text-cyan-300 border-cyan-800/50"}`}>{sh.status === "in_transit" ? "In Transit" : "Delivered"}</Badge></TableCell>
                        <TableCell>{sh.status !== "delivered" && <Button data-testid={`mark-delivered-${sh.id}`} variant="ghost" size="sm" onClick={() => handleMarkDelivered(sh.id)} className="h-7 px-2 text-[10px] text-[#555] hover:text-green-400 uppercase"><CheckCircle2 className="h-3.5 w-3.5 mr-1" />Delivered</Button>}</TableCell>
                      </TableRow>
                    ))}
                    {shipments.length === 0 && <TableRow><TableCell colSpan={7} className="text-center py-8 text-[#555]">No shipments yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* ============ CONTACTS / LEADS ============ */}
          {activeTab === "contacts" && (
            <div className="space-y-4">
              <h1 data-testid="admin-page-title" className="text-2xl font-bold uppercase tracking-tight font-['Inter'] text-white">Leads & Contacts</h1>
              <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
                <Table>
                  <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Name</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Email</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Phone</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Message</TableHead>
                    <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Date</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>
                    {contacts.map(c => (
                      <TableRow key={c.id} data-testid={`contact-row-${c.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                        <TableCell className="text-sm text-white font-medium">{c.name}</TableCell>
                        <TableCell className="text-sm text-[#888]">{c.email}</TableCell>
                        <TableCell className="text-sm text-[#888]">{c.phone || "--"}</TableCell>
                        <TableCell className="text-sm text-[#888] max-w-xs truncate">{c.message}</TableCell>
                        <TableCell className="text-[11px] text-[#555]">{new Date(c.created_at).toLocaleDateString()}</TableCell>
                      </TableRow>
                    ))}
                    {contacts.length === 0 && <TableRow><TableCell colSpan={5} className="text-center py-8 text-[#555]">No contacts yet.</TableCell></TableRow>}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* ============ DIALOGS ============ */}
      {/* Request Detail */}
      <Dialog open={!!selectedRequest} onOpenChange={() => setSelectedRequest(null)}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-2xl rounded-none">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">Request Details</DialogTitle>
            <DialogDescription className="text-[#777]">View and manage pricing.</DialogDescription>
          </DialogHeader>
          {selectedRequest && (
            <div className="space-y-5">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Customer</p><p className="text-white">{selectedRequest.name}</p></div>
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Email</p><p className="text-white">{selectedRequest.email}</p></div>
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Phone</p><p className="text-white">{selectedRequest.phone || "--"}</p></div>
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Vehicle</p><p className="text-white">{selectedRequest.vehicle_year} {selectedRequest.make} {selectedRequest.model}</p></div>
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Part</p><p className="text-white">{selectedRequest.part_needed}</p></div>
                <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Budget</p><p className="text-white">{selectedRequest.budget || "--"}</p></div>
                {selectedRequest.vin && <div><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">VIN</p><p className="text-white font-mono">{selectedRequest.vin}</p></div>}
                {selectedRequest.notes && <div className="col-span-2"><p className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1">Notes</p><p className="text-white">{selectedRequest.notes}</p></div>}
              </div>
              <div className="border-t border-#2A2A2A pt-4">
                <h4 className="text-sm font-semibold uppercase tracking-[0.1em] mb-4">Pricing & Margin</h4>
                <div className="grid grid-cols-2 gap-3">
                  <div><Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Quoted Price ($)</Label><Input data-testid="edit-quoted-price" type="number" step="0.01" value={editPricing.quoted_price} onChange={e => setEditPricing({...editPricing, quoted_price: e.target.value})} className={inputCls} /></div>
                  <div><Label className="text-[10px] text-[#555] uppercase tracking-[0.15em] mb-1.5 block">Cost Price ($)</Label><Input data-testid="edit-cost-price" type="number" step="0.01" value={editPricing.cost_price} onChange={e => setEditPricing({...editPricing, cost_price: e.target.value})} className={inputCls} /></div>
                </div>
                {editPricing.quoted_price && editPricing.cost_price && <p className="mt-2 text-sm text-[#888]">Profit: <span className={`font-semibold ${parseFloat(editPricing.quoted_price) - parseFloat(editPricing.cost_price) > 0 ? "text-green-400" : "text-red-400"}`}>${(parseFloat(editPricing.quoted_price) - parseFloat(editPricing.cost_price)).toFixed(2)}</span></p>}
                <Button data-testid="save-pricing-btn" onClick={() => handlePricingUpdate(selectedRequest.id)} className="mt-4 bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.12em] hover:bg-[#2563EB] rounded-none px-6">Save Pricing</Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Quote Dialog */}
      <Dialog open={!!quoteDialog} onOpenChange={() => setQuoteDialog(null)}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-lg rounded-none">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">Send Quote</DialogTitle>
            <DialogDescription className="text-[#777]">{quoteDialog && `${quoteDialog.vehicle_year} ${quoteDialog.make} ${quoteDialog.model} - ${quoteDialog.part_needed}`}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 mt-2">
            {quoteForm.items.map((item, i) => (
              <div key={i} className="grid grid-cols-5 gap-2">
                <div className="col-span-3"><Label className="text-[10px] text-[#555] uppercase mb-1 block">Description</Label><Input placeholder="Part" value={item.description} onChange={e => { const items = [...quoteForm.items]; items[i].description = e.target.value; setQuoteForm({...quoteForm, items}); }} className={`${inputCls} h-9`} /></div>
                <div><Label className="text-[10px] text-[#555] uppercase mb-1 block">Qty</Label><Input type="number" value={item.quantity} onChange={e => { const items = [...quoteForm.items]; items[i].quantity = parseInt(e.target.value)||1; setQuoteForm({...quoteForm, items}); }} className={`${inputCls} h-9`} /></div>
                <div><Label className="text-[10px] text-[#555] uppercase mb-1 block">Price</Label><Input type="number" step="0.01" value={item.unit_price} onChange={e => { const items = [...quoteForm.items]; items[i].unit_price = e.target.value; setQuoteForm({...quoteForm, items, total: items.reduce((s,it) => s + (parseFloat(it.unit_price)||0) * (it.quantity||1), 0).toString()}); }} className={`${inputCls} h-9`} /></div>
              </div>
            ))}
            <Button type="button" variant="ghost" size="sm" onClick={() => setQuoteForm({...quoteForm, items: [...quoteForm.items, {description:"",quantity:1,unit_price:""}]})} className="text-[11px] text-[#888] uppercase"><Plus className="h-3 w-3 mr-1" />Add Item</Button>
            <div className="grid grid-cols-2 gap-3">
              <div><Label className="text-[10px] text-[#555] uppercase mb-1 block">Total ($) *</Label><Input data-testid="quote-total" type="number" step="0.01" value={quoteForm.total} onChange={e => setQuoteForm({...quoteForm, total: e.target.value})} className={`${inputCls} font-semibold`} /></div>
              <div><Label className="text-[10px] text-[#555] uppercase mb-1 block">Est. Shipping</Label><Input value={quoteForm.estimated_shipping} onChange={e => setQuoteForm({...quoteForm, estimated_shipping: e.target.value})} className={inputCls} /></div>
            </div>
            <div><Label className="text-[10px] text-[#555] uppercase mb-1 block">Notes</Label><textarea value={quoteForm.notes} onChange={e => setQuoteForm({...quoteForm, notes: e.target.value})} rows={2} className="bg-[#1E1E1E] border border-#2A2A2A rounded-none w-full p-3 text-white text-sm resize-none outline-none focus:border-[#3B82F6]" /></div>
            <Button data-testid="submit-quote-btn" onClick={handleCreateQuote} className="w-full bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.12em] hover:bg-[#2563EB] rounded-none py-5"><Send className="h-4 w-4 mr-2" />Send Quote</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Shipment Dialog */}
      <Dialog open={!!shipmentDialog} onOpenChange={() => setShipmentDialog(null)}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-md rounded-none">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">Add Shipment</DialogTitle>
            <DialogDescription className="text-[#777]">{shipmentDialog && `Order: ${shipmentDialog.order_number}`}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 mt-2">
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Carrier *</Label><Input data-testid="shipment-carrier" value={shipmentForm.carrier} onChange={e => setShipmentForm({...shipmentForm, carrier: e.target.value})} className={inputCls} /></div>
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Tracking # *</Label><Input data-testid="shipment-tracking" value={shipmentForm.tracking_number} onChange={e => setShipmentForm({...shipmentForm, tracking_number: e.target.value})} className={`${inputCls} font-mono`} /></div>
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Est. Delivery</Label><Input data-testid="shipment-eta" value={shipmentForm.estimated_delivery} onChange={e => setShipmentForm({...shipmentForm, estimated_delivery: e.target.value})} className={inputCls} /></div>
            <Button data-testid="submit-shipment-btn" onClick={handleCreateShipment} className="w-full bg-[#3B82F6] text-white uppercase font-semibold hover:bg-[#2563EB] rounded-none py-5"><Truck className="h-4 w-4 mr-2" />Create Shipment</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Invoice Dialog */}
      <Dialog open={!!invoiceDialog} onOpenChange={() => setInvoiceDialog(null)}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-md rounded-none">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">Create Invoice</DialogTitle>
            <DialogDescription className="text-[#777]">{invoiceDialog && `Order: ${invoiceDialog.order_number}`}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 mt-2">
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Amount ($) *</Label><Input data-testid="invoice-amount" type="number" step="0.01" value={invoiceForm.amount} onChange={e => setInvoiceForm({...invoiceForm, amount: e.target.value})} className={`${inputCls} font-semibold`} /></div>
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Due Date</Label><Input data-testid="invoice-due" value={invoiceForm.due_date} onChange={e => setInvoiceForm({...invoiceForm, due_date: e.target.value})} className={inputCls} /></div>
            <div><Label className="text-[10px] text-[#555] uppercase mb-1.5 block">Notes</Label><Input value={invoiceForm.notes} onChange={e => setInvoiceForm({...invoiceForm, notes: e.target.value})} className={inputCls} /></div>
            <Button data-testid="submit-invoice-btn" onClick={handleCreateInvoice} className="w-full bg-[#3B82F6] text-white uppercase font-semibold hover:bg-[#2563EB] rounded-none py-5"><Receipt className="h-4 w-4 mr-2" />Create Invoice</Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
