import React, { useMemo, useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Download, Search, Building2, MapPin, DollarSign, Shield, Briefcase, Plus, Pencil, Trash2 } from "lucide-react";
import PageHeader from "../components/common/PageHeader";
import { Input } from "@/components/ui/input";
import RateCardModal from "../components/rates/RateCardModal";

// Define regions - these map to the notes field or can be a new field
const REGIONS = [
  "Bay Area",
  "Southern California", 
  "Northern California",
  "National"
];

function fmtCurrency(v) {
  if (typeof v !== "number" || Number.isNaN(v)) return "—";
  return v.toLocaleString(undefined, { style: "currency", currency: "USD" });
}

function downloadCSV(rows, regionName, vendorName) {
  const headers = ["Role", "Category", "Employee Wage", "Markup %", "Vendor Fee %", "Client Rate"];
  const lines = [headers.join(",")];
  for (const r of rows) {
    const cells = [
      r.role_name,
      r.category,
      r.employee_wage,
      r.markup_percentage,
      r.vendor_fee_percentage,
      r.client_rate
    ];
    lines.push(cells.join(","));
  }
  const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${vendorName}_${regionName}_Rates_${new Date().toISOString().slice(0,10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

// NEW: Helper function to parse role name into position and region
const parseRoleName = (roleName) => {
  if (!roleName) return { position: '', region: '' };
  
  // Check if role name contains a hyphen separator
  if (roleName.includes(' - ')) {
    const parts = roleName.split(' - ');
    return {
      position: parts[0].trim(),
      region: parts[1].trim()
    };
  }
  
  // If no hyphen, return the whole name as position
  return {
    position: roleName,
    region: ''
  };
};

// ==================== VENDOR-ONLY COMPONENT ====================
function VendorCompanyPricebookView({ user, vendorName }) {
  const APPROVED_TAG = "__APPROVED__";
  
  const APPROVED_RATES = ["FoodBuy", "Aramark"];
  
  const [customRateCards, setCustomRateCards] = useState([
    { name: "Bay Area Compass", baseBook: "FoodBuy", discount: 0, isDefault: true },
    { name: "LA Compass", baseBook: "FoodBuy", discount: 0, isDefault: true },
    { name: "Google", baseBook: "FoodBuy", discount: 0, isDefault: true },
    { name: "Promotion", baseBook: "FoodBuy", discount: 0, isDefault: true },
    { name: "Convention Center", baseBook: "FoodBuy", discount: 0, isDefault: true }
  ]);
  const [pricebook, setPricebook] = useState("FoodBuy");
  const [search, setSearch] = useState("");
  const [activeRegion, setActiveRegion] = useState("All");
  const [activeCategory, setActiveCategory] = useState("All");
  
  const REGIONS = ["All", "San Francisco-Oakland-San Jose", "Los Angeles-Riverside-Orange County", "Fresno", "Stockton-Lodi"];
  const [editing, setEditing] = useState(null);
  const [toast, setToast] = useState(null);
  const [analyzingCompetitiveness, setAnalyzingCompetitiveness] = useState(false);
  const [competitivenessData, setCompetitivenessData] = useState(null);
  const [showRateCardModal, setShowRateCardModal] = useState(false);
  const [editingRateCard, setEditingRateCard] = useState(null);
  const [renamingCard, setRenamingCard] = useState(null);
  const [renameValue, setRenameValue] = useState("");
  
  const RATE_CARDS = customRateCards.map(c => c.name);

  const { data: rates = [] } = useQuery({
    queryKey: ['vendor-rates-pricebook', vendorName],
    queryFn: async () => {
      const allRates = await base44.entities.VendorRate.list();
      // FOR DEMO: Show Legendary Event Staffing rates if no rates for current vendor
      const vendorRates = allRates.filter(r => r.vendor_name === vendorName && r.is_active);
      if (vendorRates.length === 0) {
        // Show demo data from Legendary Event Staffing
        return allRates.filter(r => r.vendor_name === "Legendary Event Staffing" && r.is_active);
      }
      return vendorRates;
    },
    initialData: [],
    enabled: !!vendorName,
  });

  const CATEGORIES = [
    "Kitchen and Culinary",
    "Event Staff",
    "Bartending",
    "Management",
    "Facilities",
    "Concessions",
    "Other"
  ];

  const handleSaveRateCard = (cardData) => {
    if (editingRateCard) {
      setCustomRateCards(prev => prev.map(c => c.name === editingRateCard.name ? { ...cardData, isDefault: c.isDefault } : c));
    } else {
      setCustomRateCards(prev => [...prev, { ...cardData, isDefault: false }]);
    }
    setToast(`✓ Rate card "${cardData.name}" saved successfully`);
    setPricebook(cardData.name);
    setEditingRateCard(null);
  };

  const handleDeleteRateCard = (cardName) => {
    if (customRateCards.length <= 1) {
      setToast("⚠ Cannot delete the last rate card");
      return;
    }
    setCustomRateCards(prev => prev.filter(c => c.name !== cardName));
    if (pricebook === cardName) {
      setPricebook(customRateCards.find(c => c.name !== cardName)?.name || "FoodBuy");
    }
    setToast(`✓ Rate card "${cardName}" deleted`);
  };

  const handleRenameCard = (oldName) => {
    if (!renameValue.trim() || renameValue === oldName) {
      setRenamingCard(null);
      return;
    }
    setCustomRateCards(prev => prev.map(c => c.name === oldName ? { ...c, name: renameValue.trim() } : c));
    if (pricebook === oldName) {
      setPricebook(renameValue.trim());
    }
    setToast(`✓ Renamed to "${renameValue.trim()}"`);
    setRenamingCard(null);
  };

  const scopedByBook = useMemo(() => {
    // Base approved rates
    const baseRates = {
      "FoodBuy": {
        "Banquet Captain": 47.76, "Barback": 36.13, "Barista": 43.11, "Busser": 39.23, "BW Bartender": 41.15,
        "Cashier/Standworker": 38.05, "Cook": 44.58, "Dinning Attendant": 41.56, "Dishwasher/ Steward": 38.38,
        "Executive Chef": 70.60, "FOH Cafe Attendant": 41.56, "Full Bartender": 47.76, "Grill Cook": 44.58,
        "Host/Hostess/Greeter": 41.56, "Internal Support": 41.56, "Lead Cook": 52.00, "Line Cook": 44.58,
        "Premium Server": 47.76, "Prep Cook": 37.98, "Receiver": 40.01, "Server": 41.56, "Sous Chef": 59.75,
        "Warehouse Worker": 41.15, "Baker": 44.58, "Janitor": 38.38, "Mixologist": 71.30, "Utilities": 38.38,
        "Scullery": 38.38, "Runner": 39.23, "Pantry Cook": 44.58, "Supervisor": 47.76, "Steward": 38.38, "Steward Supervisor": 41.15
      },
      "Aramark": {
        "Banquet Captain": 46.37, "Barback": 33.11, "Barista": 36.87, "Busser": 33.11, "BW Bartender": 36.12,
        "Cashier/Standworker": 33.11, "Cook": 36.12, "Dinning Attendant": 34.62, "Dishwasher/ Steward": 33.11,
        "Executive Chef": 76.76, "FOH Cafe Attendant": 34.62, "Full Bartender": 45.15, "Grill Cook": 36.12,
        "Host/Hostess/Greeter": 34.62, "Internal Support": 37.63, "Lead Cook": 52.68, "Line Cook": 36.12,
        "Premium Server": 40.64, "Prep Cook": 34.62, "Receiver": 34.62, "Server": 34.62, "Sous Chef": 60.20,
        "Warehouse Worker": 34.62, "Baker": 45.15, "Janitor": 34.62, "Mixologist": 60.20, "Utilities": 33.11,
        "Scullery": 33.11, "Runner": 33.11, "Pantry Cook": 36.12, "Supervisor": 45.15, "Steward": 33.11, "Steward Supervisor": 34.10
      }
    };
    
    // Default rate cards (built-in)
    const defaultCards = {
      "Bay Area Compass": {
        "Banquet Captain": 41.71, "Barback": 36.10, "Barista": 38.92, "Busser": 35.71, "BW Bartender": 38.92,
        "Cashier/Standworker": 36.10, "Cook": 42.13, "Dinning Attendant": 37.31, "Dishwasher/ Steward": 35.13,
        "Executive Chef": 72.19, "FOH Cafe Attendant": 37.31, "Full Bartender": 43.73, "Grill Cook": 42.13,
        "Host/Hostess/Greeter": 37.70, "Internal Support": 37.31, "Lead Cook": 46.57, "Line Cook": 42.13,
        "Premium Server": 44.12, "Prep Cook": 36.90, "Receiver": 35.71, "Server": 37.31, "Sous Chef": 56.15,
        "Warehouse Worker": 36.10, "Baker": 42.13, "Janitor": 35.13, "Mixologist": 56.15, "Utilities": 35.13,
        "Scullery": 36.10, "Runner": 35.71, "Pantry Cook": 42.13, "Supervisor": 46.84, "Steward": 36.10, "Steward Supervisor": 38.38
      },
      "LA Compass": {
        "Banquet Captain": 40.30, "Barback": 35.42, "Barista": 39.60, "Busser": 34.18, "BW Bartender": 35.65,
        "Cashier/Standworker": 34.26, "Cook": 37.20, "Dinning Attendant": 35.65, "Dishwasher/ Steward": 34.10,
        "Executive Chef": 60.53, "FOH Cafe Attendant": 35.65, "Full Bartender": 39.60, "Grill Cook": 37.20,
        "Host/Hostess/Greeter": 35.65, "Internal Support": 36.57, "Lead Cook": 39.60, "Line Cook": 37.20,
        "Premium Server": 40.30, "Prep Cook": 35.43, "Receiver": 34.65, "Server": 34.65, "Sous Chef": 52.78,
        "Warehouse Worker": 35.50, "Baker": 37.20, "Janitor": 34.10, "Mixologist": 62.00, "Utilities": 34.10,
        "Scullery": 34.10, "Runner": 34.18, "Pantry Cook": 37.20, "Supervisor": 39.60, "Steward": 34.10, "Steward Supervisor": 36.10
      },
      "Google": {
        "Banquet Captain": 34.02, "Barback": 31.79, "Barista": 32.53, "Busser": 27.62, "BW Bartender": 32.53,
        "Cashier/Standworker": 28.10, "Cook": 35.49, "Dinning Attendant": 28.83, "Dishwasher/ Steward": 28.10,
        "Executive Chef": 51.76, "FOH Cafe Attendant": 29.57, "Full Bartender": 36.97, "Grill Cook": 35.49,
        "Host/Hostess/Greeter": 29.57, "Internal Support": 36.57, "Lead Cook": 45.76, "Line Cook": 35.49,
        "Premium Server": 36.97, "Prep Cook": 29.57, "Receiver": 28.10, "Server": 30.22, "Sous Chef": 44.36,
        "Warehouse Worker": 28.10, "Baker": 35.59, "Janitor": 28.10, "Mixologist": 47.70, "Utilities": 28.10,
        "Scullery": 32.91, "Runner": 27.62, "Pantry Cook": 35.49, "Supervisor": 42.02, "Steward": 32.91, "Steward Supervisor": 34.10
      },
      "Promotion": {
        "Banquet Captain": 40.00, "Barback": 34.00, "Barista": 36.00, "Busser": 34.00, "BW Bartender": 36.00,
        "Cashier/Standworker": 34.00, "Cook": 36.00, "Dinning Attendant": 36.00, "Dishwasher/ Steward": 30.00,
        "Executive Chef": 51.00, "FOH Cafe Attendant": 36.00, "Full Bartender": 40.00, "Grill Cook": 36.00,
        "Host/Hostess/Greeter": 34.00, "Internal Support": 36.00, "Lead Cook": 45.00, "Line Cook": 36.00,
        "Premium Server": 38.00, "Prep Cook": 32.00, "Receiver": 34.00, "Server": 34.00, "Sous Chef": 44.00,
        "Warehouse Worker": 34.00, "Baker": 36.00, "Janitor": 32.00, "Mixologist": 51.00, "Utilities": 30.00,
        "Scullery": 34.00, "Runner": 34.00, "Pantry Cook": 36.00, "Supervisor": 40.00, "Steward": 34.00, "Steward Supervisor": 36.10
      },
      "Convention Center": {
        "Banquet Captain": 40.00, "Barback": 34.00, "Barista": 36.00, "Busser": 34.00, "BW Bartender": 36.00,
        "Cashier/Standworker": 34.00, "Cook": 36.00, "Dinning Attendant": 36.00, "Dishwasher/ Steward": 30.00,
        "Executive Chef": 51.00, "FOH Cafe Attendant": 36.00, "Full Bartender": 38.00, "Grill Cook": 36.00,
        "Host/Hostess/Greeter": 34.00, "Internal Support": 36.00, "Lead Cook": 45.00, "Line Cook": 36.00,
        "Premium Server": 38.00, "Prep Cook": 34.00, "Receiver": 34.00, "Server": 34.00, "Sous Chef": 44.00,
        "Warehouse Worker": 34.00, "Baker": 36.00, "Janitor": 32.00, "Mixologist": 51.00, "Utilities": 30.00,
        "Scullery": 34.00, "Runner": 34.00, "Pantry Cook": 36.00, "Supervisor": 40.00, "Steward": 34.00, "Steward Supervisor": 38.38
      }
    };

    // Add custom rate cards
    const customCardsRates = {};
    customRateCards.forEach(card => {
      customCardsRates[card.name] = card.rates;
    });
    
    const ratesByBook = { ...baseRates, ...defaultCards, ...customCardsRates };
    
    const currentBookRates = ratesByBook[pricebook] || {};
    const isCustomRateCard = RATE_CARDS.includes(pricebook);
    
    // For Custom Rate Cards, deduplicate by position name only
    if (isCustomRateCard) {
      const uniquePositions = new Map();
      
      rates.forEach(r => {
        const parsed = parseRoleName(r.role_name);
        const position = parsed.position;
        const finalRate = currentBookRates[position] || r.client_rate;
        
        // Only keep first occurrence of each position
        if (!uniquePositions.has(position)) {
          uniquePositions.set(position, {
            ...r,
            client: pricebook,
            region: "—",
            approvedCap: r.approved_cap_rate || r.client_rate,
            proposedRate: finalRate,
            position: position, // Use clean position name without region
            markupPct: r.markup_percentage,
            volDiscountPct: r.vendor_fee_percentage
          });
        }
      });
      
      return Array.from(uniquePositions.values());
    }
    
    // For Approved Rates, keep regions
    return rates.map(r => {
      const parsed = parseRoleName(r.role_name);
      const position = parsed.position;
      const finalRate = currentBookRates[position] || r.client_rate;
      const assignedRegion = r.region || parsed.region || (r.notes?.includes("Bay Area") ? "Bay Area" : "LA");
      
      return {
        ...r,
        client: pricebook,
        region: assignedRegion,
        approvedCap: r.approved_cap_rate || r.client_rate,
        proposedRate: finalRate,
        position: r.role_name,
        markupPct: r.markup_percentage,
        volDiscountPct: r.vendor_fee_percentage
      };
    });
  }, [rates, pricebook]);

  const isApprovedRate = APPROVED_RATES.includes(pricebook);
  
  const filtered = useMemo(() => {
    return scopedByBook.filter(r => {
      const regionMatch = !isApprovedRate || activeRegion === "All" || r.region === activeRegion || parseRoleName(r.position).region === activeRegion;
      const categoryMatch = activeCategory === "All" || r.category === activeCategory;
      const searchMatch = search.trim() === "" || parseRoleName(r.position).position.toLowerCase().includes(search.toLowerCase());
      return regionMatch && categoryMatch && searchMatch;
    });
  }, [scopedByBook, activeRegion, activeCategory, search, isApprovedRate]);

  const kpis = useMemo(() => {
    const rateValues = filtered.map(r => r.proposedRate);
    const avg = rateValues.length ? rateValues.reduce((a, b) => a + b, 0) / rateValues.length : 0;
    const min = rateValues.length ? Math.min(...rateValues) : 0;
    const max = rateValues.length ? Math.max(...rateValues) : 0;
    const total = filtered.length;
    return { avg, min, max, total };
  }, [filtered]);

  async function analyzeCompetitiveness() {
    setAnalyzingCompetitiveness(true);
    try {
      const positionsToAnalyze = filtered.slice(0, 20); // Limit to 20 positions for API
      const prompt = `You are a staffing industry pricing expert. Analyze these ${pricebook} hourly rates for the California market competitiveness.

RATES TO ANALYZE:
${positionsToAnalyze.map(r => `- ${parseRoleName(r.position).position}: $${r.proposedRate}/hr`).join('\n')}

For EACH position listed above, provide market analysis:
- marketRate: typical California market rate for this role (number)
- score: competitiveness score 0-100 (100 = most competitive/best value)
- status: exactly one of "Highly Competitive", "Competitive", "Average", "Above Market"
- recommendation: brief 5-10 word suggestion

Consider Bay Area/LA market rates. Food service roles typically $28-50/hr, management $45-80/hr.`;

      const result = await base44.integrations.Core.InvokeLLM({
        prompt,
        add_context_from_internet: true,
        response_json_schema: {
          type: "object",
          properties: {
            analysis: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  position: { type: "string" },
                  marketRate: { type: "number" },
                  score: { type: "number" },
                  status: { type: "string" },
                  recommendation: { type: "string" }
                }
              }
            }
          }
        }
      });

      setCompetitivenessData(result.analysis || []);
      setToast("✓ Competitive analysis complete");
    } catch (error) {
      console.error("Analysis error:", error);
      setToast("⚠ Analysis failed. Try again.");
    } finally {
      setAnalyzingCompetitiveness(false);
    }
  }

  function exportCSV() {
    const headers = ["Pricebook", "Position", "Category", "Region", "ApprovedCap", "ProposedRate", "Markup%", "VolDiscount%"];
    const body = filtered.map(r => {
      const parsed = parseRoleName(r.position); // Parse role_name for export
      return [
        pricebook,
        parsed.position,
        r.category,
        parsed.region,
        r.approvedCap,
        r.proposedRate,
        r.markupPct,
        r.volDiscountPct
      ];
    });
    const csv = [headers, ...body]
      .map(row => row.map(v => (typeof v === "string" ? `"${v}"` : v)).join(","))
      .join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `service-rates-${pricebook}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-slate-50">
      {/* Header */}
      <header className="px-6 py-8 border-b bg-white/80 backdrop-blur-xl sticky top-0 z-10 shadow-sm">
        <div className="max-w-7xl mx-auto">
          <div className="flex items-start justify-between mb-4">
            <div>
              <div className="flex items-center gap-3 mb-2">
                <div className="w-12 h-12 bg-blue-600 rounded-2xl flex items-center justify-center shadow-lg">
                                    <DollarSign className="w-7 h-7 text-white" />
                                  </div>
                <div>
                  <h1 className="text-3xl font-bold text-slate-900">Service Rate Management</h1>
                  <p className="text-sm text-slate-500">2025–2028 Pricing Structure</p>
                </div>
              </div>
              <p className="text-slate-600 ml-15">
                {rates.length > 0 && rates[0].vendor_name !== vendorName ? (
                  <>Viewing demo data from <span className="font-semibold text-blue-600">Legendary Event Staffing</span></>
                ) : (
                  <>Managing rates for <span className="font-semibold text-blue-600">{vendorName}</span></>
                )}
              </p>
            </div>
            <div className="flex gap-3">
              <Button 
                                onClick={analyzeCompetitiveness} 
                                disabled={analyzingCompetitiveness}
                                className="bg-blue-600 hover:bg-blue-700 text-white shadow-lg px-6"
                              >
                {analyzingCompetitiveness ? (
                  <>
                    <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Analyzing Market...
                  </>
                ) : (
                  <>
                    <svg className="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                    AI Price Check
                  </>
                )}
              </Button>
              <Button onClick={exportCSV} variant="outline" className="border-slate-300 bg-white hover:bg-slate-50 shadow-sm">
                <Download className="w-4 h-4 mr-2" />
                Export
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Pricebook Tabs - Split into Approved Rates and Rate Cards */}
      <section className="max-w-7xl mx-auto px-6 mt-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Approved Enterprise Rates */}
          <div className="bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl shadow-lg border-2 border-amber-200 p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-amber-500 rounded-xl flex items-center justify-center shadow-md">
                                    <Shield className="w-6 h-6 text-white" />
                                  </div>
              <div>
                <h3 className="text-sm font-bold text-amber-900 uppercase tracking-wider">Approved Enterprise Rates</h3>
                <p className="text-xs text-amber-700">Varies by region</p>
              </div>
            </div>
            <div className="flex flex-wrap gap-2">
              {APPROVED_RATES.map(tab => (
                <button
                  key={tab}
                  onClick={() => {
                    setPricebook(tab);
                    setActiveRegion("All");
                  }}
                  className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                                          pricebook === tab
                                            ? "bg-amber-600 text-white shadow-lg"
                                            : "bg-white text-slate-700 hover:bg-amber-50 border border-amber-200"
                                        }`}
                >
                  {tab}
                </button>
              ))}
            </div>
          </div>

          {/* Custom Rate Cards */}
          <div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-2xl shadow-lg border-2 border-blue-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center shadow-md">
                                      <Briefcase className="w-6 h-6 text-white" />
                                    </div>
                <div>
                  <h3 className="text-sm font-bold text-blue-900 uppercase tracking-wider">Custom Rate Cards</h3>
                  <p className="text-xs text-blue-700">Client-specific & negotiated</p>
                </div>
              </div>
              <Button 
                                  onClick={() => { setEditingRateCard(null); setShowRateCardModal(true); }}
                                  size="sm"
                                  className="bg-blue-600 hover:bg-blue-700 text-white shadow-md"
                                >
                <Plus className="w-4 h-4 mr-1" />
                New Card
              </Button>
            </div>
            <div className="flex flex-wrap gap-2">
              {RATE_CARDS.map(tab => {
                const cardData = customRateCards.find(c => c.name === tab);
                const isRenaming = renamingCard === tab;
                
                if (isRenaming) {
                  return (
                    <div key={tab} className="flex items-center gap-1">
                      <input
                        type="text"
                        value={renameValue}
                        onChange={(e) => setRenameValue(e.target.value)}
                        onBlur={() => handleRenameCard(tab)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') handleRenameCard(tab);
                          if (e.key === 'Escape') setRenamingCard(null);
                        }}
                        autoFocus
                        className="px-3 py-2 rounded-xl text-sm font-semibold border-2 border-blue-500 bg-white focus:outline-none w-40"
                      />
                    </div>
                  );
                }
                
                return (
                  <div key={tab} className="relative group">
                    <button
                      onClick={() => setPricebook(tab)}
                      onDoubleClick={(e) => { e.stopPropagation(); setRenamingCard(tab); setRenameValue(tab); }}
                      className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                        pricebook === tab
                          ? "bg-blue-600 text-white shadow-lg"
                          : "bg-white text-slate-700 hover:bg-blue-50 border border-blue-200"
                      }`}
                      title="Double-click to rename"
                    >
                      {tab}
                      {cardData?.discount > 0 && (
                        <span className="ml-2 text-xs opacity-80">-{cardData.discount}%</span>
                      )}
                    </button>
                    <div className="absolute -top-2 -right-2 hidden group-hover:flex gap-1">
                      <button
                        onClick={(e) => { e.stopPropagation(); setRenamingCard(tab); setRenameValue(tab); }}
                        className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center shadow-md hover:bg-blue-600"
                        title="Rename"
                      >
                        <Pencil className="w-3 h-3" />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleDeleteRateCard(tab); }}
                        className="w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center shadow-md hover:bg-red-600"
                        title="Delete"
                      >
                        <Trash2 className="w-3 h-3" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </section>

      {/* Competitiveness Summary */}
      {competitivenessData && competitivenessData.length > 0 && (
        <section className="max-w-7xl mx-auto px-6 mt-6">
                    <div className="bg-slate-800 rounded-3xl p-8 shadow-2xl">
            <div className="flex items-center gap-4 mb-6">
                            <div className="w-14 h-14 bg-white/20 backdrop-blur-xl rounded-2xl flex items-center justify-center shadow-lg">
                              <svg className="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                              </svg>
                            </div>
                            <div>
                              <h3 className="text-2xl font-bold text-white">AI Market Intelligence</h3>
                              <p className="text-purple-100">Real-time competitive analysis for {pricebook}</p>
                            </div>
                          </div>
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            {[
                              { status: "Highly Competitive", color: "bg-green-500", textColor: "text-green-600" },
                              { status: "Competitive", color: "bg-blue-500", textColor: "text-blue-600" },
                              { status: "Average", color: "bg-yellow-500", textColor: "text-yellow-600" },
                              { status: "Above Market", color: "bg-red-500", textColor: "text-red-600" }
                            ].map(({ status, color, textColor }) => {
                              const count = competitivenessData.filter(d => d.status === status).length;
                              return (
                                <div key={status} className="bg-white/95 backdrop-blur-xl rounded-2xl p-6 shadow-xl border border-white/20 hover:scale-105 transition-transform">
                                  <div className="flex items-center gap-3 mb-3">
                                    <div className={`w-4 h-4 rounded-full ${color}`} />
                                    <p className={`text-4xl font-bold ${textColor}`}>{count}</p>
                                  </div>
                                  <p className="text-sm font-semibold text-slate-700">{status}</p>
                                  <div className="mt-3 h-2 bg-slate-100 rounded-full overflow-hidden">
                                    <div className={`h-full ${color} rounded-full`} style={{ width: `${(count / competitivenessData.length) * 100}%` }} />
                                  </div>
                                </div>
                              );
                            })}
                          </div>
          </div>
        </section>
      )}

      {/* KPI Cards */}
      <section className="max-w-7xl mx-auto px-6 mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-blue-600 rounded-2xl shadow-xl p-6 text-white relative overflow-hidden">
                      <div className="relative">
            <div className="flex items-center gap-2 mb-2">
              <DollarSign className="w-5 h-5 opacity-80" />
              <p className="text-sm font-medium opacity-90">Average Rate</p>
            </div>
            <p className="text-4xl font-bold mb-2">{fmtCurrency(kpis.avg)}</p>
            <p className="text-sm opacity-75">Based on {kpis.total} positions</p>
          </div>
        </div>

        <div className="bg-purple-600 rounded-2xl shadow-xl p-6 text-white relative overflow-hidden">
                      <div className="relative">
            <div className="flex items-center gap-2 mb-2">
              <Building2 className="w-5 h-5 opacity-80" />
              <p className="text-sm font-medium opacity-90">Total Positions</p>
            </div>
            <p className="text-4xl font-bold mb-2">{kpis.total}</p>
            <p className="text-sm opacity-75">{pricebook} rate book</p>
          </div>
        </div>

        <div className="bg-emerald-600 rounded-2xl shadow-xl p-6 text-white relative overflow-hidden">
                      <div className="relative">
            <div className="flex items-center gap-2 mb-2">
              <MapPin className="w-5 h-5 opacity-80" />
              <p className="text-sm font-medium opacity-90">Price Range</p>
            </div>
            <p className="text-3xl font-bold mb-2">
              {fmtCurrency(kpis.min)} – {fmtCurrency(kpis.max)}
            </p>
            <p className="text-sm opacity-75">Min – Max spread</p>
          </div>
        </div>
      </section>

      {/* Region Filters - Only for Approved Enterprise Rates */}
      {isApprovedRate && (
        <section className="max-w-7xl mx-auto px-6 mt-6">
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-6">
            <div className="flex items-center gap-2 mb-4">
              <MapPin className="w-5 h-5 text-emerald-600" />
              <h3 className="text-sm font-bold text-slate-700 uppercase tracking-wider">Service Regions</h3>
            </div>
            <div className="flex items-center flex-wrap gap-3">
              {REGIONS.map(region => (
                <button
                  key={region}
                  onClick={() => setActiveRegion(region)}
                  className={`px-5 py-2.5 rounded-xl text-sm font-semibold border-2 transition-all ${
                                          activeRegion === region
                                            ? "bg-emerald-600 text-white border-emerald-600 shadow-lg"
                                            : "bg-white text-slate-700 border-slate-200 hover:border-emerald-300 hover:bg-emerald-50"
                                        }`}
                >
                  {region}
                </button>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Category Filters + Search */}
      <section className="max-w-7xl mx-auto px-6 mt-6">
        <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-bold text-slate-700 flex items-center gap-2">
              <Search className="w-4 h-4" />
              CATEGORY & SEARCH
            </h3>
            {(search || activeCategory !== "All" || activeRegion !== "All") && (
              <button
                onClick={() => {
                  setSearch("");
                  setActiveCategory("All");
                  setActiveRegion("All");
                }}
                className="text-xs text-blue-600 hover:text-blue-700 font-medium"
              >
                Clear all filters
              </button>
            )}
          </div>
          <div className="flex items-center flex-wrap gap-3">
            {["All", ...CATEGORIES].map(cat => (
              <button
                key={cat}
                onClick={() => setActiveCategory(cat)}
                className={`px-4 py-2.5 rounded-xl text-sm font-medium border-2 transition-all ${
                                      activeCategory === cat
                                        ? "bg-slate-800 text-white border-slate-900 shadow-lg"
                                        : "bg-slate-50 text-slate-700 border-slate-200 hover:border-slate-300 hover:bg-slate-100"
                                    }`}
              >
                {cat}
              </button>
            ))}
          </div>
          <div className="mt-4">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
              <Input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search positions..."
                className="pl-12 h-12 bg-slate-50 border-slate-200 rounded-xl text-base"
              />
            </div>
          </div>
        </div>
      </section>

      {/* Table */}
      <section className="max-w-7xl mx-auto px-6 mt-6 mb-8">
        <div className="overflow-hidden rounded-2xl shadow-xl bg-white border border-slate-200">
          <div className="bg-slate-800 px-6 py-4">
            <h3 className="text-white font-bold text-lg">Rate Breakdown</h3>
            <p className="text-slate-300 text-sm">Detailed pricing for {pricebook}</p>
          </div>
          <table className="w-full text-left">
            <thead className="bg-gradient-to-r from-slate-50 to-slate-100 border-b-2 border-slate-200">
              <tr className="text-slate-700 text-xs font-bold uppercase tracking-wider">
                <th className="px-6 py-4">Position</th>
                <th className="px-6 py-4">Category</th>
                <th className="px-6 py-4">Region</th>
                <th className="px-6 py-4">Base Wage</th>
                <th className="px-6 py-4">{pricebook} Rate</th>
                <th className="px-6 py-4">Market Rate</th>
                <th className="px-6 py-4">Competitive Score</th>
                <th className="px-6 py-4 text-center">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, idx) => {
                const parsed = parseRoleName(r.position);
                const competitive = competitivenessData?.find(c => c.position === parsed.position);
                const isEditing = editing === r.id;
                
                return (
                  <tr key={r.id || idx} className={`border-b border-slate-100 transition-all hover:bg-blue-50/30 ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/50'}`}>
                    <td className="px-6 py-5">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center text-white font-bold text-sm shadow-md">
                          {parsed.position.substring(0, 2).toUpperCase()}
                        </div>
                        <span className="font-bold text-slate-900">{parsed.position}</span>
                      </div>
                    </td>
                    <td className="px-6 py-5">
                      <Badge className="bg-slate-100 text-slate-700 border border-slate-200 text-xs font-semibold px-3 py-1">
                        {r.category}
                      </Badge>
                    </td>
                    <td className="px-6 py-5">
                      <span className="text-sm text-slate-600 flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {r.region}
                      </span>
                    </td>
                    <td className="px-6 py-5">
                      <span className="text-sm font-semibold text-slate-700">{fmtCurrency(r.employee_wage)}</span>
                    </td>
                    <td className="px-6 py-5">
                      {isEditing ? (
                        <input
                          type="number"
                          step="0.01"
                          defaultValue={r.proposedRate}
                          className="w-28 px-3 py-2 border-2 border-blue-300 rounded-lg font-semibold text-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
                          onBlur={(e) => {
                            setEditing(null);
                            setToast("✓ Rate updated successfully");
                          }}
                        />
                      ) : (
                        <div className="flex items-center gap-2">
                          <span className="text-xl font-bold text-blue-600">{fmtCurrency(r.proposedRate)}</span>
                          <span className="text-xs text-slate-500">/hr</span>
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-5">
                      {competitive ? (
                        <div className="flex items-center gap-2">
                          <div>
                            <span className="font-semibold text-slate-900">{fmtCurrency(competitive.marketRate)}</span>
                            <div className={`inline-flex items-center ml-2 px-2 py-0.5 rounded-full text-xs font-bold ${
                              r.proposedRate < competitive.marketRate 
                                ? 'bg-green-100 text-green-700' 
                                : 'bg-red-100 text-red-700'
                            }`}>
                              {r.proposedRate < competitive.marketRate ? '↓' : '↑'} 
                              {Math.abs(((r.proposedRate - competitive.marketRate) / competitive.marketRate * 100)).toFixed(1)}%
                            </div>
                          </div>
                        </div>
                      ) : (
                        <span className="text-slate-400 text-sm italic">Run AI analysis</span>
                      )}
                    </td>
                    <td className="px-6 py-5">
                      {competitive ? (
                        <div className="flex items-center gap-3">
                          <div className={`w-4 h-4 rounded-full shadow-md ${
                                                          competitive.status === 'Highly Competitive' ? 'bg-green-500' :
                                                          competitive.status === 'Competitive' ? 'bg-blue-500' :
                                                          competitive.status === 'Average' ? 'bg-yellow-500' : 
                                                          'bg-red-500'
                                                        }`} />
                          <div>
                            <div className="text-lg font-bold text-slate-900">{competitive.score}</div>
                            <div className="text-xs text-slate-500 font-medium">{competitive.status}</div>
                          </div>
                        </div>
                      ) : (
                        <span className="text-slate-300">—</span>
                      )}
                    </td>
                    <td className="px-6 py-5">
                      <div className="flex items-center justify-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setEditing(isEditing ? null : r.id)}
                          className={`${isEditing ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'} font-semibold px-4`}
                        >
                          {isEditing ? '✓ Save' : 'Edit'}
                        </Button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr>
                  <td className="px-4 py-8 text-center text-slate-500" colSpan={8}>
                    No rates found for {pricebook} rate book. {search.trim() && "Try adjusting your search or "}Switch to a different rate book.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </section>

      {/* Toast */}
      {toast && (
        <div className="fixed bottom-8 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-sm px-6 py-3 rounded-2xl shadow-2xl z-50 flex items-center gap-3 animate-in slide-in-from-bottom-5">
          <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
          {toast}
          <button className="ml-2 opacity-70 hover:opacity-100 font-bold" onClick={() => setToast(null)}>✕</button>
        </div>
      )}

      {/* Rate Card Modal */}
      <RateCardModal
        isOpen={showRateCardModal}
        onClose={() => { setShowRateCardModal(false); setEditingRateCard(null); }}
        onSave={handleSaveRateCard}
        editingCard={editingRateCard}
      />
    </div>
  );
}

// ==================== ADMIN/PROCUREMENT VIEW (EXISTING) ====================
function AdminProcurementRatesView({ vendorName }) {
  const [activeRegion, setActiveRegion] = useState("Bay Area");
  const [searchQuery, setSearchQuery] = useState("");

  const { data: rates = [], isLoading } = useQuery({
    queryKey: ['vendor-rates', vendorName],
    queryFn: async () => {
      const allRates = await base44.entities.VendorRate.list();
      return allRates.filter(r => r.vendor_name === vendorName && r.is_active);
    },
    initialData: [],
    enabled: !!vendorName,
  });

  const ratesByRegion = useMemo(() => {
    const grouped = {};
    
    rates.forEach(rate => {
      let region = "National"; // Default region
      
      // Attempt to determine region from rate.notes first
      if (rate.notes) {
        const notesLower = rate.notes.toLowerCase();
        if (notesLower.includes("bay area") || notesLower.includes("san francisco")) {
          region = "Bay Area";
        } else if (notesLower.includes("southern california") || notesLower.includes("los angeles") || notesLower.includes("san diego")) {
          region = "Southern California";
        } else if (notesLower.includes("northern california") || notesLower.includes("sacramento")) {
          region = "Northern California";
        }
      }
      
      // If region is not determined by notes, try to parse from role_name
      if (region === "National" && parseRoleName(rate.role_name).region) {
          region = parseRoleName(rate.role_name).region;
      }

      if (!grouped[region]) {
        grouped[region] = [];
      }
      grouped[region].push(rate);
    });
    
    return grouped;
  }, [rates]);

  const filteredRates = useMemo(() => {
    const regionRates = ratesByRegion[activeRegion] || [];
    if (!searchQuery.trim()) return regionRates;
    
    const query = searchQuery.toLowerCase();
    return regionRates.filter(r => 
      parseRoleName(r.role_name).position.toLowerCase().includes(query) || // Search parsed position
      r.category?.toLowerCase().includes(query)
    );
  }, [ratesByRegion, activeRegion, searchQuery]);

  const regionStats = useMemo(() => {
    const regionRates = ratesByRegion[activeRegion] || [];
    return {
      totalRoles: regionRates.length,
      avgClientRate: regionRates.length > 0 
        ? regionRates.reduce((sum, r) => sum + (r.client_rate || 0), 0) / regionRates.length 
        : 0,
      avgMarkup: regionRates.length > 0
        ? regionRates.reduce((sum, r) => sum + (r.markup_percentage || 0), 0) / regionRates.length
        : 0,
      avgVendorFee: regionRates.length > 0
        ? regionRates.reduce((sum, r) => sum + (r.vendor_fee_percentage || 0), 0) / regionRates.length
        : 0
    };
  }, [ratesByRegion, activeRegion]);

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader 
          title={`Service Rates 2025-2028`}
          subtitle={`${vendorName} - Manage pricing across all clients and positions`}
          actions={
            <Button
              onClick={() => downloadCSV(filteredRates, activeRegion, vendorName)}
              variant="outline"
              className="border-slate-300"
            >
              <Download className="w-4 h-4 mr-2" />
              Export {activeRegion} Rates
            </Button>
          }
        />

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Total Roles</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.totalRoles}</p>
                </div>
                <Building2 className="w-8 h-8 text-[#0A39DF]" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg Client Rate</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{fmtCurrency(regionStats.avgClientRate)}</p>
                </div>
                <DollarSign className="w-8 h-8 text-emerald-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg Markup</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.avgMarkup.toFixed(1)}%</p>
                </div>
                <MapPin className="w-8 h-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg VA Fee</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.avgVendorFee.toFixed(1)}%</p>
                </div>
                <DollarSign className="w-8 h-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Region Tabs */}
        <Card className="mb-6 border-slate-200">
          <CardContent className="p-4">
            <div className="flex flex-wrap gap-2">
              {REGIONS.filter(region => ratesByRegion[region]?.length > 0).map(region => (
                <button
                  key={region}
                  onClick={() => setActiveRegion(region)}
                  className={`px-6 py-3 rounded-lg text-sm font-medium transition-all ${
                    activeRegion === region
                      ? "bg-[#0A39DF] text-white shadow-md"
                      : "bg-white text-slate-600 border border-slate-200 hover:border-[#0A39DF] hover:text-[#0A39DF]"
                  }`}
                >
                  {region}
                  <Badge variant="secondary" className="ml-2 bg-slate-100 text-slate-700">
                    {ratesByRegion[region]?.length || 0}
                  </Badge>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Search Bar */}
        <div className="mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
            <Input
              placeholder="Search roles or categories..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 bg-white border-slate-200"
            />
          </div>
        </div>

        {/* Rates Table */}
        <Card className="border-slate-200 shadow-sm">
          <CardHeader className="border-b border-slate-100 bg-gradient-to-br from-slate-50 to-white">
            <CardTitle className="text-lg font-semibold text-slate-900 flex items-center gap-2">
              <MapPin className="w-5 h-5 text-[#0A39DF]" />
              {activeRegion} Rates
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {filteredRates.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-slate-50 border-b-2 border-slate-200">
                    <tr>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Position</th>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Category</th>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Region</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Employee Wage</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Markup</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">VA Fee</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Client Rate</th>
                      <th className="text-center py-4 px-6 font-semibold text-sm text-slate-700">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredRates.map((rate, idx) => {
                      const parsed = parseRoleName(rate.role_name);
                      
                      return (
                        <tr 
                          key={rate.id} 
                          className={`border-b border-slate-100 hover:bg-slate-50 transition-colors ${
                            idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'
                          }`}
                        >
                          <td className="py-4 px-6">
                            <p className="font-semibold text-[#1C323E]">{parsed.position}</p>
                          </td>
                          <td className="py-4 px-6">
                            <Badge variant="outline" className="text-xs">
                              {rate.category}
                            </Badge>
                          </td>
                          <td className="py-4 px-6">
                            <p className="text-sm text-slate-600">{parsed.region || '—'}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-slate-900">{fmtCurrency(rate.employee_wage)}</p>
                            <p className="text-xs text-slate-500">/hour</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-blue-600">{rate.markup_percentage}%</p>
                            <p className="text-xs text-slate-500">+{fmtCurrency(rate.employee_wage * (rate.markup_percentage / 100))}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-purple-600">{rate.vendor_fee_percentage}%</p>
                            <p className="text-xs text-slate-500">+{fmtCurrency((rate.employee_wage * (1 + rate.markup_percentage / 100)) * (rate.vendor_fee_percentage / 100))}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="text-2xl font-bold text-[#0A39DF]">{fmtCurrency(rate.client_rate)}</p>
                            <p className="text-xs text-slate-500">/hour</p>
                          </td>
                          <td className="py-4 px-6 text-center">
                            <div className="flex flex-col gap-1 items-center">
                              {rate.competitive_status && (
                                <Badge className="bg-green-100 text-green-700 text-xs">
                                  Competitive
                                </Badge>
                              )}
                              {rate.minimum_wage_compliance && (
                                <Badge className="bg-emerald-100 text-emerald-700 text-xs">
                                  Compliant
                                </Badge>
                              )}
                              {rate.csta_compliant && (
                                <Badge className="bg-blue-100 text-blue-700 text-xs">
                                  CSTA
                                </Badge>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-16">
                <MapPin className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                <h3 className="text-xl font-semibold text-slate-900 mb-2">
                  {searchQuery ? "No matching rates found" : `No rates for ${activeRegion}`}
                </h3>
                <p className="text-slate-600">
                  {searchQuery ? "Try adjusting your search" : "Contact your account manager to set up rates for this region"}
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Footer Info */}
        <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-start gap-3">
            <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
              <Building2 className="w-4 h-4 text-blue-600" />
            </div>
            <div>
              <h4 className="font-semibold text-slate-900 mb-1">About Your Rates</h4>
              <p className="text-sm text-slate-700">
                These are your approved service rates for {activeRegion}. Rates include employee wages, markup, and vendor administration fees. 
                All rates are compliant with regional minimum wage requirements and have been approved by procurement.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== MAIN COMPONENT WITH ROLE-BASED ROUTING ====================
export default function VendorRates() {
  const { data: user } = useQuery({
    queryKey: ['current-user-vendor-rates'],
    queryFn: () => base44.auth.me(),
  });

  const userRole = user?.user_role || user?.role || "admin";
  const vendorName = user?.company_name || "Vendor";
  const isVendor = userRole === "vendor";

  // VENDOR ROLE: Show new company pricebook interface
  if (isVendor) {
    return <VendorCompanyPricebookView user={user} vendorName={vendorName} />;
  }

  // ALL OTHER ROLES: Show existing region-based rates view
  return <AdminProcurementRatesView vendorName={vendorName} />;
}