// React via CDN, JSX compiled in-browser by Babel Standalone

const sideNav = [];

const sections = [];

// Default catalog used for search/filter. Each item describes a course offering.
const defaultCatalog = [];
function inferDisplayDuration(name, level, field, durationYears) {
  if (durationYears && durationYears > 0) return durationYears;
  const n = (name || '').toLowerCase();
  const lvl = (level || '').toLowerCase();
  const fld = (field || '').toLowerCase();
  if (n.includes('b.arch') || n.includes('architecture')) return 5.0;
  if (lvl === 'diploma') return 3.0;
  if (lvl === 'pg') return 2.0;
  if (fld === 'engineering' || n.includes('b.tech') || n.includes('b.e') || n.includes('engineering')) return 4.0;
  if (n.includes('b.pharm') || n.includes('pharmacy')) return 4.0;
  if (lvl === 'ug') return 3.0;
  return 3.0;
}

// Helper function to safely parse JSON responses (prevents HTML error pages from being parsed as JSON)
async function safeJsonParse(response) {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const text = await response.text();
  
  // Check if response looks like HTML (common error page indicator)
  const trimmedText = text.trim();
  if (trimmedText.startsWith('<') || trimmedText.startsWith('<!DOCTYPE') || trimmedText.startsWith('<html')) {
    throw new Error(`Server returned HTML instead of JSON. Response: ${trimmedText.substring(0, 200)}`);
  }
  
  // Try to parse as JSON
  try {
    return JSON.parse(text);
  } catch (e) {
    // If parsing fails, check if it looks like HTML error
    if (trimmedText.includes('<br') || trimmedText.includes('<b>') || trimmedText.includes('</html>')) {
      throw new Error(`Server returned HTML error page instead of JSON. Response: ${trimmedText.substring(0, 200)}`);
    }
    throw new Error(`Invalid JSON response: ${trimmedText.substring(0, 100)}`);
  }
}

// Helper function to try parsing JSON from any response (including error responses) for error message extraction
async function tryParseJsonFromResponse(response) {
  const contentType = response.headers.get('content-type');
  if (contentType && contentType.includes('application/json')) {
    const text = await response.text();
    try {
      return JSON.parse(text);
    } catch (_) {
      return null;
    }
  }
  return null;
}

function useFinderOptions() {
  const [opts, setOpts] = React.useState({ categories: [], exams: [], rounds: [], inst_types: [], cities: [], programs: [], regions: [], years: [] });
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        // Fetch options and catalog in parallel; merge programs to be robust
        const [rOpts, rCat] = await Promise.allSettled([
          fetch('api/finder_options.php?t=' + Date.now()), // Add cache-busting parameter
          fetch('api/catalog.php')
        ]);

        let base = null;
        if (rOpts.status === 'fulfilled' && rOpts.value && rOpts.value.ok) {
          try {
            base = await safeJsonParse(rOpts.value);
            console.log('Finder options loaded:', base); // Debug log
          } catch (_) {}
        }
        if (!cancelled && base) {
          console.log('Cities loaded:', base.cities); // Debug cities specifically
          setOpts(base);
        }

        let names = [];
        if (rCat.status === 'fulfilled' && rCat.value && rCat.value.ok) {
          try {
            const cat = await safeJsonParse(rCat.value);
            // Filter to only engineering courses (field = 'Engineering' or name contains 'Engineering'/'ENGG')
            names = Array.from(new Set((Array.isArray(cat) ? cat : [])
              .filter(c => {
                if (!c || !c.name) return false;
                const nameUpper = String(c.name).toUpperCase();
                const fieldUpper = String(c.field || '').toUpperCase();
                return fieldUpper === 'ENGINEERING' || 
                       nameUpper.includes('ENGINEERING') || 
                       nameUpper.includes('ENGG');
              })
              .map(c => c && c.name)
              .filter(Boolean))).sort();
          } catch (_) {}
        }
        if (!cancelled && names.length) {
          setOpts(prev => {
            const merged = Array.from(new Set([...(prev.programs || []), ...names])).sort();
            return { ...prev, programs: merged };
          });
        }
      } catch (_) {}
    })();
    return () => { cancelled = true; };
  }, []);
  return opts;
}

function RankFinderPage() {
  const { categories, exams, rounds, inst_types, cities, programs, regions, years } = useFinderOptions();
  const [rank, setRank] = React.useState('');
  const [exam, setExam] = React.useState('');
  const [category, setCategory] = React.useState('OPEN'); // Default to OPEN
  const [round, setRound] = React.useState(''); // Always empty - show all rounds
  const [instType, setInstType] = React.useState('');
  const [city, setCity] = React.useState('');
  const [program, setProgram] = React.useState('');
  const [programChoices, setProgramChoices] = React.useState([]);
  const [selectedCourses, setSelectedCourses] = React.useState([]);
  const [selectedColleges, setSelectedColleges] = React.useState([]);
  const [collegeCutoffs, setCollegeCutoffs] = React.useState([]);
  const [isLoadingCutoffs, setIsLoadingCutoffs] = React.useState(false);
  const [allColleges, setAllColleges] = React.useState([]); // All available colleges
  
  
  // User Preferences & Saved Data
  const [userProfile, setUserProfile] = React.useState({
    name: '',
    email: '',
    homeCity: '',
    preferences: {
      preferredCities: [],
      maxFee: 500000,
      minReputation: 0
    }
  });
  const [savedSearches, setSavedSearches] = React.useState([]);
  const [shortlistedColleges, setShortlistedColleges] = React.useState([]);
  
  const [showQuickActions, setShowQuickActions] = React.useState(false);
  
  // Comparison Tool States
  const [comparisonColleges, setComparisonColleges] = React.useState([]);
  const [showComparison, setShowComparison] = React.useState(false);
  
  // Analytics States
  const [admissionProbabilities, setAdmissionProbabilities] = React.useState({});
  const [trendData, setTrendData] = React.useState([]);
  const [showAnalytics, setShowAnalytics] = React.useState(false);
  
  // Enhanced college cutoff display states
  const [cutoffViewMode, setCutoffViewMode] = React.useState('cards'); // 'cards', 'table', 'compact'
  const [cutoffPage, setCutoffPage] = React.useState(1);
  const [cutoffPageSize, setCutoffPageSize] = React.useState(6); // Programs per page
  const [cutoffSortBy, setCutoffSortBy] = React.useState('closing_rank'); // 'closing_rank', 'course_name', 'competition_level'
  const [cutoffSortOrder, setCutoffSortOrder] = React.useState('asc'); // 'asc', 'desc'
  const [cutoffSearchTerm, setCutoffSearchTerm] = React.useState('');
  // const [region, setRegion] = React.useState(''); // REMOVED as per user request
  const [year, setYear] = React.useState('2025');
  
  // Course-based college search states
  const [selectedCourseForColleges, setSelectedCourseForColleges] = React.useState('');
  const [selectedCityForColleges, setSelectedCityForColleges] = React.useState('');
  const [collegesByCourse, setCollegesByCourse] = React.useState([]);
  const [isLoadingCollegesByCourse, setIsLoadingCollegesByCourse] = React.useState(false);
  const [collegePage, setCollegePage] = React.useState(1);
  const [collegePageSize, setCollegePageSize] = React.useState(10);
  
  // Function to fetch colleges by course and city
  const fetchCollegesByCourse = React.useCallback(async (course, city = '') => {
    if (!course) {
      setCollegesByCourse([]);
      setLiveData({});
      return;
    }
    
    setIsLoadingCollegesByCourse(true);
    try {
      let fetchUrl = `api/colleges_by_course.php?course=${encodeURIComponent(course)}&t=${Date.now()}`;
      if (city) {
        fetchUrl += `&city=${encodeURIComponent(city)}`;
      }
      console.log(`📡 Fetching colleges for course: "${course}"${city ? `, city: "${city}"` : ''}`);
      console.log(`🔗 URL: ${fetchUrl}`);
      
      const response = await fetch(fetchUrl);
      console.log(`📨 Response status: ${response.status} ${response.statusText}`);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await safeJsonParse(response);
      console.log(`📦 API Response:`, data);
      console.log(`📊 Data structure:`, {
        hasColleges: 'colleges' in data,
        collegesType: Array.isArray(data.colleges) ? 'array' : typeof data.colleges,
        collegesLength: Array.isArray(data.colleges) ? data.colleges.length : 'N/A',
        dataKeys: Object.keys(data)
      });
      
      const colleges = data.colleges || [];
      console.log(`✅ Extracted ${colleges.length} colleges`);
      
      if (colleges.length === 0) {
        console.warn(`⚠️ No colleges returned for course: "${course}"${city ? `, city: "${city}"` : ''}`);
        console.warn(`   API response:`, data);
      }
      
      setCollegesByCourse(colleges);
      
      // Automatically fetch live data for ALL colleges with websites
      if (colleges.length > 0) {
        console.log(`🚀 Starting automatic fetch for ${colleges.length} colleges`);
        let collegesWithWebsite = 0;
        const fetchPromises = [];
        
        // Fetch data for all colleges with websites
        colleges.forEach((college, index) => {
          // Check if college has a valid website (more lenient validation)
          const website = college.website ? String(college.website).trim() : '';
          const hasWebsite = website && 
                            website !== '#' && 
                            website !== '' &&
                            !website.startsWith('#') &&
                            website.length > 3 &&
                            (website.includes('.') || website.startsWith('http'));
          
          if (hasWebsite) {
            collegesWithWebsite++;
            
            // Create fetch function
            const fetchLiveData = async () => {
              try {
                setFetchingLiveData(prev => ({...prev, [college.id]: true}));
                console.log(`[${index + 1}/${colleges.length}] 🌐 Fetching live data for: ${college.name} (ID: ${college.id}, Website: ${website})`);
                
                const fetchUrl = `api/fetch_college_data_live.php?id=${college.id}&t=${Date.now()}`;
                console.log(`📡 Making fetch request to: ${fetchUrl}`);
                
                const liveResponse = await fetch(fetchUrl);
                console.log(`📨 Response status: ${liveResponse.status} ${liveResponse.statusText}`);
                
                const liveDataResult = await safeJsonParse(liveResponse);
                
                console.log(`📥 Live data result for ${college.name}:`, liveDataResult);
                
                if (liveDataResult && liveDataResult.fetched_data) {
                  const fetched = liveDataResult.fetched_data;
                  console.log(`✅ Fetched data for ${college.name}:`, fetched);
                  
                  // Set data if we got anything
                  if (fetched.hostel_facilities || fetched.fees || fetched.contact_info) {
                    setLiveData(prev => {
                      const newData = {
                        ...prev,
                        [college.id]: {
                          hostel: fetched.hostel_facilities || null,
                          fees: fetched.fees || null,
                          contact: fetched.contact_info || null
                        }
                      };
                      console.log(`✓ Updated liveData for ${college.name}:`, newData[college.id]);
                      return newData;
                    });
                  } else {
                    console.log(`⚠️ No data found for ${college.name}`);
                  }
                } else {
                  console.log(`⚠️ No fetched_data in response for ${college.name}:`, liveDataResult);
                }
              } catch (error) {
                console.error(`❌ Error fetching live data for college ${college.id} (${college.name}):`, error);
                console.error(`   Error details:`, error.message, error.stack);
              } finally {
                setFetchingLiveData(prev => ({...prev, [college.id]: false}));
              }
            };
            
            // For first 5 colleges, fetch immediately; others with delay
            if (index < 5) {
              fetchPromises.push(fetchLiveData());
            } else {
              setTimeout(() => {
                fetchPromises.push(fetchLiveData());
              }, (index - 4) * 300); // 300ms delay after first 5
            }
          } else {
            console.log(`⏭️ Skipping ${college.name} - no valid website (${website || 'N/A'})`);
          }
        });
        
        console.log(`📊 Total colleges with websites: ${collegesWithWebsite} out of ${colleges.length}`);
        console.log(`🔄 Started fetching for first ${Math.min(5, collegesWithWebsite)} colleges immediately`);
        
        // Log sample of colleges being processed
        if (colleges.length > 0) {
          console.log(`📋 Sample colleges:`, colleges.slice(0, 3).map(c => ({
            id: c.id,
            name: c.name,
            website: c.website
          })));
        }
      }
    } catch (error) {
      console.error('Error fetching colleges by course:', error);
      setCollegesByCourse([]);
    } finally {
      setIsLoadingCollegesByCourse(false);
    }
  }, []);
  const [expandedCollegeId, setExpandedCollegeId] = React.useState(null);
  const [liveData, setLiveData] = React.useState({}); // Store live fetched data: {collegeId: {hostel, fees, contact}}
  const [fetchingLiveData, setFetchingLiveData] = React.useState({}); // Track which colleges are being fetched
  const [rows, setRows] = React.useState([]);
  const [metadata, setMetadata] = React.useState(null);
  const [isSearching, setIsSearching] = React.useState(false);
  const [error, setError] = React.useState('');
  const [hasAttemptedSearch, setHasAttemptedSearch] = React.useState(false);
  const lastAbortRef = React.useRef(null);
  
  // Notifications state
  const [notifications, setNotifications] = React.useState([]);
  const [showAllNotifications, setShowAllNotifications] = React.useState(false);
  
  // Approved Boards state
  const [approvedBoards, setApprovedBoards] = React.useState([]);
  const [boardStates, setBoardStates] = React.useState([]);
  const [boardFilter, setBoardFilter] = React.useState('');
  const [boardSearch, setBoardSearch] = React.useState('');
  const [showApprovedBoards, setShowApprovedBoards] = React.useState(false);
  const [isLoadingBoards, setIsLoadingBoards] = React.useState(false);
  
  // Fetch notifications on component mount
  React.useEffect(() => {
    fetch('api/admissions.php')
      .then(safeJsonParse)
      .then(data => {
        const notifs = data?.ug_engineering?.notifications || [];
         // Sort notifications by date (newest first), then by id (descending) to ensure latest is first
        const sortedNotifs = Array.isArray(notifs) ? notifs.sort((a, b) => {
          const dateA = new Date(a.date || 0);
          const dateB = new Date(b.date || 0);
          if (dateB.getTime() !== dateA.getTime()) {
            return dateB.getTime() - dateA.getTime(); // Newest first
          }
          return (b.id || 0) - (a.id || 0); // Higher ID first if dates are equal
        }) : [];
        setNotifications(sortedNotifs);
      })
      .catch(() => setNotifications([]));
  }, []);
  
  // Fetch approved boards on component mount
  React.useEffect(() => {
    setIsLoadingBoards(true);
    fetch('api/approved_boards.php')
      .then(safeJsonParse)
      .then(data => {
        if (data.success) {
          setApprovedBoards(Array.isArray(data.boards) ? data.boards : []);
          setBoardStates(Array.isArray(data.states) ? data.states : []);
        }
      })
      .catch(() => {
        setApprovedBoards([]);
        setBoardStates([]);
      })
      .finally(() => setIsLoadingBoards(false));
  }, []);
  
  // Filter approved boards based on state filter and search
  const filteredBoards = React.useMemo(() => {
    let filtered = [...approvedBoards];
    
    if (boardFilter) {
      filtered = filtered.filter(b => 
        b.state_ut && b.state_ut.toLowerCase().includes(boardFilter.toLowerCase())
      );
    }
    
    if (boardSearch) {
      filtered = filtered.filter(b => 
        (b.board_name && b.board_name.toLowerCase().includes(boardSearch.toLowerCase())) ||
        (b.state_ut && b.state_ut.toLowerCase().includes(boardSearch.toLowerCase()))
      );
    }
    
    return filtered;
  }, [approvedBoards, boardFilter, boardSearch]);
  
  // Category normalization function - standardize category names for display
  const normalizeCategoryDisplay = React.useCallback((cat) => {
    if (!cat) return cat;
    const catUpper = String(cat).toUpperCase().trim();
    // Map common variations to standard names
    const categoryMap = {
      'GEN': 'OPEN',
      'GENERAL': 'OPEN',
      'OPEN': 'OPEN',
      'SC': 'SC',
      'ST': 'ST',
      'SEBC': 'SEBC',
      'OBC': 'SEBC',
      'EWS': 'EWS',
      'ESM': 'ESM',
      'TFWS': 'TFWS',
      'PH': 'PH',
      'PWD': 'PH'
    };
    return categoryMap[catUpper] || cat;
  }, []);
  
  // Helper function to format rank values - show "-" instead of 0 or empty
  const formatRank = React.useCallback((rank, formattedRank) => {
    // Check formatted rank first
    if (formattedRank && formattedRank !== '0' && formattedRank !== 0 && formattedRank !== '') {
      return formattedRank;
    }
    // Check unformatted rank
    if (rank && rank !== '0' && rank !== 0 && rank !== '') {
      const rankNum = typeof rank === 'string' ? parseInt(rank.replace(/[,\s]/g, ''), 10) : rank;
      if (!isNaN(rankNum) && rankNum > 0) {
        return rank;
      }
    }
    // Return dash if no valid rank
    return '—';
  }, []);
  
  // Normalize and prepare parameters for API
  const normalizedParams = React.useMemo(() => {
    const trim = (s) => (s || '').toString().trim();
    const up = (s) => trim(s).toUpperCase();
    let cat = up(category);
    // Preserve GEN for backend SP; mapping to OPEN is done server-side for LAR
    let ex = up(exam);
    if (ex !== 'GUJCET' && ex !== 'JEE') ex = ex || 'GUJCET';
    const params = new URLSearchParams();
    const rnk = parseInt(trim(rank), 10);
    if (!isNaN(rnk) && rnk > 0) params.set('rank', String(rnk));
    
    // Always send all parameters, even if empty, for proper filtering
    params.set('exam', ex || '');
    params.set('category', cat || '');
    params.set('round', trim(round) || '');
    params.set('inst_type', trim(instType) || '');
    params.set('city', trim(city) || '');
    // Handle multiple course selection
    if (selectedCourses.length > 0) {
      params.set('courses', selectedCourses.join(','));
    } else {
      params.set('program', trim(program) || '');
    }
    // params.set('region', trim(region) || ''); // REMOVED as per user request
    
    const yr = parseInt(String(year || '').trim(), 10);
    if (!isNaN(yr) && yr > 0) params.set('year', String(yr));
    
    // Debug: Log what parameters are being sent
    console.log('Search parameters:', Object.fromEntries(params));
    console.log('Category value:', category);
    console.log('Normalized category:', cat);
    
    return params;
  }, [rank, exam, category, round, instType, city, program, selectedCourses, year]);
  // Pagination state
  const [page, setPage] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);

  // Do not auto-default filters; keep them empty unless user selects
  // Do not auto-select Program; user must choose explicitly
  // Default other dropdowns to first available option when options load
  // Do not auto-default filters; keep them empty (ALL) unless user selects
  // Do not auto-select Round; user must choose explicitly
  // Do not auto-default Institute Type; keep it empty (ALL) unless user selects
  // Region auto-defaulting removed as per user request
  // Build Program choices by merging options API and catalog course names
  // Filter to show only engineering courses
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const base = Array.isArray(programs) ? programs.slice() : [];
        let merged = base;
        try {
          const rc = await fetch('api/catalog.php');
          if (rc.ok) {
            const cat = await safeJsonParse(rc);
            // Filter to only engineering courses (field = 'Engineering' or name contains 'Engineering'/'ENGG')
            const names = Array.from(new Set((Array.isArray(cat) ? cat : [])
              .filter(c => {
                if (!c || !c.name) return false;
                const nameUpper = String(c.name).toUpperCase();
                const fieldUpper = String(c.field || '').toUpperCase();
                return fieldUpper === 'ENGINEERING' || 
                       nameUpper.includes('ENGINEERING') || 
                       nameUpper.includes('ENGG');
              })
              .map(c => c && c.name)
              .filter(Boolean)));
            merged = Array.from(new Set([...(base || []), ...names])).sort();
          }
        } catch (_) {}
        if (!cancelled) {
          setProgramChoices(merged);
        }
      } catch (_) {}
    })();
    return () => { cancelled = true; };
  }, [programs]);

  // Reset to first page when filters change
  React.useEffect(() => { setPage(1); }, [rank, exam, category, round, instType, city, program, pageSize]);
  // Region page reset removed as per user request
  React.useEffect(() => { setPage(1); }, [year]);
  
  // Reset cutoff page when data changes
  React.useEffect(() => { setCutoffPage(1); }, [collegeCutoffs, cutoffSearchTerm, cutoffSortBy, cutoffSortOrder]);
  
  // Load all colleges on component mount
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const response = await fetch('api/colleges.php?t=' + Date.now());
        if (response.ok) {
          const data = await safeJsonParse(response);
          if (!cancelled && data && Array.isArray(data.all_colleges)) {
            setAllColleges(data.all_colleges);
          }
        }
      } catch (error) {
        console.error('Failed to load colleges:', error);
      }
    })();
    return () => { cancelled = true; };
  }, []);
  
  // Helper functions for college cutoff processing
  const processCollegeCutoffs = React.useMemo(() => {
    if (!collegeCutoffs || collegeCutoffs.length === 0) return { processedColleges: [], totalPrograms: 0 };
    
    let allPrograms = [];
    
    // Flatten all programs from all colleges
    collegeCutoffs.forEach(college => {
      college.programs.forEach(program => {
        allPrograms.push({
          ...program,
          college_name: college.college_name,
          college_index: collegeCutoffs.indexOf(college)
        });
      });
    });
    
    // Apply search filter
    if (cutoffSearchTerm) {
      allPrograms = allPrograms.filter(program => 
        program.course_name.toLowerCase().includes(cutoffSearchTerm.toLowerCase()) ||
        program.college_name.toLowerCase().includes(cutoffSearchTerm.toLowerCase()) ||
        program.category?.toLowerCase().includes(cutoffSearchTerm.toLowerCase()) ||
        program.round?.toLowerCase().includes(cutoffSearchTerm.toLowerCase())
      );
    }
    
    // Apply sorting
    allPrograms.sort((a, b) => {
      let aVal, bVal;
      
      switch (cutoffSortBy) {
        case 'closing_rank':
          aVal = parseInt(a.closing_rank) || 999999;
          bVal = parseInt(b.closing_rank) || 999999;
          break;
        case 'course_name':
          aVal = a.course_name.toLowerCase();
          bVal = b.course_name.toLowerCase();
          break;
        case 'competition_level':
          const levelOrder = { 'Very High': 1, 'High': 2, 'Medium': 3, 'Low': 4, 'Very Low': 5 };
          aVal = levelOrder[a.competition_level] || 6;
          bVal = levelOrder[b.competition_level] || 6;
          break;
        default:
          aVal = a[cutoffSortBy];
          bVal = b[cutoffSortBy];
      }
      
      if (cutoffSortOrder === 'desc') {
        return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
      } else {
        return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
      }
    });
    
    // Apply pagination
    const startIndex = (cutoffPage - 1) * cutoffPageSize;
    const endIndex = startIndex + cutoffPageSize;
    const paginatedPrograms = allPrograms.slice(startIndex, endIndex);
    
    // Group paginated programs back by college
    const processedColleges = [];
    const collegeMap = new Map();
    
    paginatedPrograms.forEach(program => {
      if (!collegeMap.has(program.college_name)) {
        collegeMap.set(program.college_name, {
          college_name: program.college_name,
          programs: []
        });
      }
      collegeMap.get(program.college_name).programs.push(program);
    });
    
    return {
      processedColleges: Array.from(collegeMap.values()),
      totalPrograms: allPrograms.length,
      totalPages: Math.ceil(allPrograms.length / cutoffPageSize)
    };
  }, [collegeCutoffs, cutoffSearchTerm, cutoffSortBy, cutoffSortOrder, cutoffPage, cutoffPageSize]);

  // Compute year choices with a safe fallback to current/last year
  const yearChoices = React.useMemo(() => {
    if (Array.isArray(years) && years.length > 0) return years;
    const now = new Date().getFullYear();
    return [now, now - 1];
  }, [years]);
  // Keep year empty by default to allow backend to choose best dataset

  // Instant search on input (debounced, abortable)
  React.useEffect(() => {
    const id = setTimeout(() => {
      const rnk = parseInt(String(rank || '').trim(), 10);
      const hasValidRank = !isNaN(rnk) && rnk > 0;
      const selectedYear = parseInt(String(year || '').trim(), 10);
      const isYear2024 = !isNaN(selectedYear) && selectedYear === 2024;
      
      // Rank is mandatory UNLESS year 2024 is selected (show all data like home page)
      if (!hasValidRank && !isYear2024) { 
        console.log('No search: Rank is required (or select year 2024)');
        // Don't set error here - only show error if user has attempted to search
        setRows([]); 
        setMetadata(null);
        return; 
      }
      
      // Mark that a search attempt is being made
      setHasAttemptedSearch(true);
      
      // Round selection removed - always show all rounds
      
      console.log('Executing search with params:', Object.fromEntries(normalizedParams));
      (async () => {
        setIsSearching(true); 
        setError(''); // Clear any previous errors
        // Abort previous in-flight request
        if (lastAbortRef.current) { try { lastAbortRef.current.abort(); } catch (_) {} }
        const ac = new AbortController();
        lastAbortRef.current = ac;
        try {
          const r = await fetch('api/rank_finder.php?' + normalizedParams.toString(), { signal: ac.signal });
          if (!r.ok) {
            let msg = 'Search failed';
            try { const j = await tryParseJsonFromResponse(r); if (j && j.error) msg = j.error; } catch (_) {}
            throw new Error(msg);
          }
          const data = await safeJsonParse(r);
          console.log('API Response:', data);
          console.log('Results count:', Array.isArray(data) ? data.length : (data.results ? data.results.length : 0));
          // Debug: Log first result to check open_rank
          const firstResult = Array.isArray(data) ? data[0] : (data.results ? data.results[0] : null);
          if (firstResult) {
            console.log('First result - College:', firstResult.college);
            console.log('First result - open_rank:', firstResult.open_rank, 'open_rank_formatted:', firstResult.open_rank_formatted);
            console.log('First result - closing_rank:', firstResult.closing_rank, 'closing_rank_formatted:', firstResult.closing_rank_formatted);
          }
          
          // Filter out invalid records
          const filterValidRecords = (rows) => {
            if (!Array.isArray(rows)) return [];
            const userRank = parseInt(String(rank || '').trim(), 10);
            const hasValidRank = !isNaN(userRank) && userRank > 0;
            const isYear2024View = parseInt(String(year || '').trim(), 10) === 2024 && !hasValidRank;
            
            return rows.filter(r => {
              // Check if closing rank is null/empty (placeholder row from API when no data available)
              const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
              const closingRank = parseInt(closingRankStr, 10);
              const hasClosingRank = !isNaN(closingRank) && closingRank > 0;
              
              // Allow records with null/empty closing_rank (these are placeholder rows when no data is available)
              // Only filter out records with closing_rank = 0 (invalid data, not placeholder)
              if (r.closing_rank === 0 || (r.closing_rank_formatted === '0' && hasClosingRank === false)) {
                return false; // Exclude records with closing_rank explicitly set to 0
              }
              
              // If user entered a rank and record has a valid closing rank, check eligibility (closing_rank >= user_rank)
              // Skip this check for placeholder rows (null/empty closing_rank) or if viewing year 2024 without rank
              if (hasValidRank && !isYear2024View && hasClosingRank) {
                if (userRank > closingRank) {
                  return false; // User rank is worse than closing rank, not eligible
                }
              }
              
              // Filter out records with invalid college names
              const collegeName = String(r.college || r.college_name || '').trim();
              if (!collegeName || collegeName === '—' || collegeName === '') {
                return false; // Exclude empty college names
              }
              
              // Filter out placeholder/invalid college names
              const invalidPatterns = [
                /^first year/i,
                /^engineering\s+\d{4}/i,
                /^year\s+\d{4}/i,
                /^\d{4}-\d{2,4}$/i, // Just years like "2025-26"
                /^program/i,
                /^course/i
              ];
              
              if (invalidPatterns.some(pattern => pattern.test(collegeName))) {
                return false; // Exclude invalid college name patterns
              }
              
              return true; // Valid record (including placeholder rows with null closing_rank)
            });
          };
          
          // Handle both old format (array) and new format (object with results)
          let validRows = [];
          if (Array.isArray(data)) {
            validRows = filterValidRecords(data);
            setRows(validRows);
          } else if (data && Array.isArray(data.results)) {
            validRows = filterValidRecords(data.results);
            setRows(validRows);
            // Store metadata if available
            if (data.metadata) {
              setMetadata(data.metadata);
            }
          } else {
            setRows([]);
          }
          
          console.log('Valid results after filtering:', validRows.length);
        } catch (e) {
          if (e.name !== 'AbortError') { setError(e.message || 'Search failed'); setRows([]); }
        } finally {
          setIsSearching(false);
        }
      })();
    }, 400);
    return () => clearTimeout(id);
  }, [normalizedParams, rank, exam, category, round, instType, city, program, year]);

  const search = async () => {
      // Mark that user has attempted to search
      setHasAttemptedSearch(true);
      
      const rnk = parseInt(String(rank || '').trim(), 10);
      const hasValidRank = !isNaN(rnk) && rnk > 0;
      const selectedYear = parseInt(String(year || '').trim(), 10);
      const isYear2024 = !isNaN(selectedYear) && selectedYear === 2024;
      
      // Rank is mandatory UNLESS year 2024 is selected (show all data like home page)
      if (!hasValidRank && !isYear2024) {
      setError('Please enter your rank to search');
      setRows([]); 
      setMetadata(null);
      return; 
    }
    
    // Round selection removed - always show all rounds
    
    console.log('Manual search executing with params:', Object.fromEntries(normalizedParams));
    
    setIsSearching(true); 
    setError(''); // Clear any previous errors
    try {
      // Abort previous in-flight request
      if (lastAbortRef.current) { try { lastAbortRef.current.abort(); } catch (_) {} }
      const ac = new AbortController();
      lastAbortRef.current = ac;
      const r = await fetch('api/rank_finder.php?' + normalizedParams.toString(), { signal: ac.signal });
      if (!r.ok) {
        let msg = 'Search failed';
        try { const j = await tryParseJsonFromResponse(r); if (j && j.error) msg = j.error; } catch (_) {}
        throw new Error(msg);
      }
      const data = await safeJsonParse(r);
      console.log('Manual search API Response:', data);
      console.log('Manual search Results count:', Array.isArray(data) ? data.length : (data.results ? data.results.length : 0));
      
      // Frontend deduplication: Remove duplicates based on college_id and course_id
      // Also filter out invalid records
      const filterValidRecords = (rows) => {
        if (!Array.isArray(rows)) return [];
        const userRank = parseInt(String(rank || '').trim(), 10);
        const hasValidRank = !isNaN(userRank) && userRank > 0;
        const isYear2024View = parseInt(String(year || '').trim(), 10) === 2024 && !hasValidRank;
        
        return rows.filter(r => {
          // Check if closing rank is null/empty (placeholder row from API when no data available)
          const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
          const closingRank = parseInt(closingRankStr, 10);
          const hasClosingRank = !isNaN(closingRank) && closingRank > 0;
          
          // Allow records with null/empty closing_rank (these are placeholder rows when no data is available)
          // Only filter out records with closing_rank = 0 (invalid data, not placeholder)
          if (r.closing_rank === 0 || (r.closing_rank_formatted === '0' && hasClosingRank === false)) {
            return false; // Exclude records with closing_rank explicitly set to 0
          }
          
          // If user entered a rank and record has a valid closing rank, check eligibility (closing_rank >= user_rank)
          // Skip this check for placeholder rows (null/empty closing_rank) or if viewing year 2024 without rank
          if (hasValidRank && !isYear2024View && hasClosingRank) {
            if (userRank > closingRank) {
              return false; // User rank is worse than closing rank, not eligible
            }
          }
          
          // Filter out records with invalid college names
          const collegeName = String(r.college || r.college_name || '').trim();
          if (!collegeName || collegeName === '—' || collegeName === '') {
            return false; // Exclude empty college names
          }
          
          // Filter out placeholder/invalid college names
          const invalidPatterns = [
            /^first year/i,
            /^engineering\s+\d{4}/i,
            /^year\s+\d{4}/i,
            /^\d{4}-\d{2,4}$/i, // Just years like "2025-26"
            /^program/i,
            /^course/i
          ];
          
          if (invalidPatterns.some(pattern => pattern.test(collegeName))) {
            return false; // Exclude invalid college name patterns
          }
          
          return true; // Valid record (including placeholder rows with null closing_rank)
        });
      };
      
      let processedData = [];
      if (Array.isArray(data)) {
        processedData = filterValidRecords(data);
      } else if (data && Array.isArray(data.results)) {
        processedData = filterValidRecords(data.results);
      }
      
      // Deduplication logic - ensure only one record per college-course combination
      const uniqueRows = [];
      const seen = new Set();
      
      processedData.forEach(row => {
        const key = `${row.college_id}-${row.course_id}`;
        if (!seen.has(key)) {
          seen.add(key);
          uniqueRows.push(row);
        }
      });
      
      // Handle both old format (array) and new format (object with results)
      if (Array.isArray(data)) {
        setRows(uniqueRows);
        setMetadata({ total: uniqueRows.length, original_total: data.length });
      } else if (data && Array.isArray(data.results)) {
        setRows(uniqueRows);
        setMetadata({ ...data.metadata, total: uniqueRows.length, original_total: data.results.length });
      } else {
        setRows([]);
        setMetadata(null);
      }
      
      console.log('Valid results after filtering:', uniqueRows.length);
      
      // Debug logging
      console.log(`Search completed: ${uniqueRows.length} unique results (${processedData.length} total before deduplication)`);
    } catch (e) { if (e.name !== 'AbortError') { setError(e.message || 'Search failed.'); setRows([]); } }
    finally { setIsSearching(false); }
  };
  
  const fetchCollegeCutoffs = async () => {
    if (selectedColleges.length === 0) return;
    
    console.log('Fetching cutoffs for colleges:', selectedColleges);
    setIsLoadingCutoffs(true);
    try {
      const params = new URLSearchParams();
      params.set('colleges', selectedColleges.join('|')); // Use | as delimiter instead of comma
      params.set('year', year || '2025');
      
      console.log('API URL:', `api/college_cutoffs.php?${params}`);
      
      const response = await fetch(`api/college_cutoffs.php?${params}`);
      if (!response.ok) throw new Error('Failed to fetch college cutoffs');
      
      const data = await safeJsonParse(response);
      console.log('Received data:', data);
      setCollegeCutoffs(data);
    } catch (e) {
      console.error('Error fetching college cutoffs:', e);
      setError('Failed to load college cutoffs');
    } finally {
      setIsLoadingCutoffs(false);
    }
  };
  
  const total = rows.length;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  const startIdx = (page - 1) * pageSize;
  const endIdx = startIdx + pageSize;
  const visibleRows = rows.slice(startIdx, endIdx);

  return (
    <>
      <style>{`
        @keyframes float {
          0%, 100% { transform: translateY(0px) rotate(0deg); }
          50% { transform: translateY(-20px) rotate(180deg); }
        }
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(-10px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
      <div className="container rank-finder-container">
      <div className="search-card">
        <div className="search-header">
          <h3>🎯 Rank-based College Finder</h3>
          <p>Enter your details to discover colleges where you can get admission based on your rank</p>
        </div>
        <div className="search-form">
          <div className="form-row">
            <div className="form-group">
              <label>ACPC Merit Rank *</label>
              <input type="number" min="1" value={rank} onChange={e=>setRank(e.target.value)} placeholder="e.g., 12345" />
              <small style={{fontSize:'11px', color:'#6b7280', marginTop:'4px', display:'block'}}>Common merit rank issued by ACPC (same for all categories)</small>
            </div>
            <div className="form-group">
              <label>Seat Category *</label>
              <select value={category} onChange={e=>setCategory(e.target.value)}>
                <option value="">ALL</option>
                {categories.filter(c => c !== 'ALL').map(c => <option key={c} value={c}>{c}</option>)}
              </select>
              <small style={{fontSize:'11px', color:'#6b7280', marginTop:'4px', display:'block'}}>Category refers to seat reservation, not a separate rank</small>
            </div>
            <div className="form-group">
              <label>Counselling Year *</label>
              <select value={year} onChange={e=>setYear(e.target.value)}>
                <option value="2025">2025</option>
                {yearChoices.filter(y => y !== '2025').map(y => <option key={y} value={y}>{y}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label>Institute Type</label>
              <select value={instType} onChange={e=>setInstType(e.target.value)}>
                <option value="">ALL</option>
                {inst_types.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label>Program (Select up to 5) *</label>
              <div style={{position:'relative'}}>
                <select 
                  value="" 
                  onChange={e=>{
                    const value = e.target.value;
                    if (value && !selectedCourses.includes(value) && selectedCourses.length < 5) {
                      setSelectedCourses([...selectedCourses, value]);
                    }
                  }}
                  style={{width:'100%', padding:'8px', borderRadius:'8px', border:'1px solid #ddd'}}
                >
                  <option value="">Select Program to Add</option>
                  {programChoices.filter(p => !selectedCourses.includes(p)).map(p => <option key={p} value={p}>{p}</option>)}
                </select>
                {selectedCourses.length > 0 && (
                  <div style={{marginTop:'8px', display:'flex', flexWrap:'wrap', gap:'4px'}}>
                    {selectedCourses.map((course, index) => (
                      <span key={index} style={{
                        background:'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        color:'white',
                        padding:'4px 8px',
                        borderRadius:'12px',
                        fontSize:'12px',
                        display:'flex',
                        alignItems:'center',
                        gap:'4px'
                      }}>
                        {course}
                        <button 
                          onClick={()=>setSelectedCourses(selectedCourses.filter((_,i)=>i!==index))}
                          style={{background:'rgba(255,255,255,0.2)', border:'none', color:'white', borderRadius:'50%', width:'16px', height:'16px', cursor:'pointer'}}
                        >
                          ×
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
            <div className="form-group">
              <label>City</label>
              <select value={city} onChange={e=>setCity(e.target.value)}>
                <option value="">ALL</option>
                {cities && cities.length > 0 ? (
                  cities.map(c => <option key={c} value={c}>{c}</option>)
                ) : (
                  <option disabled>Loading cities...</option>
                )}
              </select>
            </div>
          </div>
          
          {/* Helper text note */}
          <div style={{
            marginTop: '16px',
            padding: '12px 16px',
            background: 'rgba(59, 130, 246, 0.1)',
            border: '1px solid rgba(59, 130, 246, 0.2)',
            borderRadius: '8px',
            fontSize: '12px',
            color: '#1e40af',
            lineHeight: '1.6'
          }}>
            <strong>Note:</strong> ACPC merit rank is common for all categories. Category selection is used only to evaluate eligibility for reserved seats.
          </div>
          
          <div className="search-actions" style={{display:'flex',gap:'10px',justifyContent:'center'}}>
            <div style={{marginTop: '20px', display: 'flex', gap: '10px', justifyContent: 'center'}}>
              <button 
                className="btn btn-primary btn-lg" 
                onClick={search} 
                disabled={isSearching || (!rank && !(parseInt(String(year || '').trim(), 10) === 2024)) || (rank && parseInt(String(rank || '').trim(), 10) <= 0)}
                style={{
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  border: 'none',
                  padding: '12px 24px',
                  borderRadius: '10px',
                  fontSize: '16px',
                  fontWeight: '600',
                  boxShadow: '0 4px 15px rgba(102, 126, 234, 0.3)'
                }}
              >
                {isSearching ? '🔍 Searching...' : '🎯 Find Colleges'}
              </button>
              
              
              <button 
                className="btn btn-info btn-lg" 
                onClick={() => setShowAnalytics(!showAnalytics)}
                style={{
                  background: 'linear-gradient(135deg, #17a2b8 0%, #138496 100%)',
                  border: 'none',
                  padding: '12px 20px',
                  borderRadius: '10px',
                  fontSize: '14px',
                  fontWeight: '600',
                  boxShadow: '0 4px 15px rgba(23, 162, 184, 0.3)'
                }}
              >
                📊 Analytics
              </button>
            </div>
            <button className="btn btn-lg" onClick={()=>{ 
              setRank(''); 
              setExam(''); 
              setCategory('OPEN'); // Reset to OPEN (default)
              setRound(''); 
              setInstType(''); 
              setCity(''); 
              setProgram(''); 
              setSelectedCourses([]); 
              setSelectedColleges([]); 
              setCollegeCutoffs([]); 
              setYear('2025'); 
              setRows([]); 
              setError(''); 
              setHasAttemptedSearch(false); // Reset search attempt flag
              // Reset cutoff display states
              setCutoffViewMode('cards');
              setCutoffPage(1);
              setCutoffSearchTerm('');
              setCutoffSortBy('closing_rank');
              setCutoffSortOrder('asc');
              // Note: allColleges is not reset as it should persist
            }} 
            disabled={isSearching}
            style={{
              background: 'var(--white)',
              border: '2px solid var(--border)',
              color: 'var(--dark)',
              padding: '14px 24px',
              borderRadius: '12px',
              fontSize: '15px',
              fontWeight: '600',
              transition: 'all 0.3s ease'
            }}
            onMouseEnter={(e) => {
              e.target.style.background = 'var(--light-gray)';
              e.target.style.borderColor = 'var(--gray)';
            }}
            onMouseLeave={(e) => {
              e.target.style.background = 'var(--white)';
              e.target.style.borderColor = 'var(--border)';
            }}
          >
            🗑️ Clear All
          </button>
            </div>
          </div>
        </div>
      </div>

      {/* Results Table - Only show if rank is entered OR year 2024 is selected */}
      {((rank && parseInt(String(rank || '').trim(), 10) > 0) || (parseInt(String(year || '').trim(), 10) === 2024)) && (() => {
        const isYear2024View = parseInt(String(year || '').trim(), 10) === 2024 && (!rank || parseInt(String(rank || '').trim(), 10) <= 0);
        // Determine which round is being used (from metadata or first result)
        const roundUsed = metadata?.round_used || (rows.length > 0 ? rows[0]?.round : null);
        const roundLabel = roundUsed ? 
          (roundUsed.toLowerCase().includes('vacant') ? 'Vacant Round (Final Counselling Round)' : 
           roundUsed.toLowerCase().includes('round 3') || roundUsed.toLowerCase().includes('round-3') ? 'Round 3 (Last Available Counselling Round)' :
           roundUsed.toLowerCase().includes('round 2') || roundUsed.toLowerCase().includes('round-2') ? 'Round 2 (Last Available Counselling Round)' :
           roundUsed.toLowerCase().includes('round 1') || roundUsed.toLowerCase().includes('round-1') ? 'Round 1 (Last Available Counselling Round)' :
           roundUsed) : 'Last Available Counselling Round';
        return (
        <div className="rank-finder-table-container">
          {/* Results banner */}
          {rows.length > 0 && (
            <div style={{
              marginBottom: '20px',
              padding: '14px 18px',
              background: 'linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%)',
              border: '1px solid rgba(59, 130, 246, 0.3)',
              borderRadius: '10px',
              fontSize: '13px',
              color: '#1e40af',
              lineHeight: '1.6'
            }}>
              <div style={{fontWeight: '600', marginBottom: '6px'}}>
                Results based on {roundLabel} of the selected year
              </div>
              <div style={{fontSize: '12px', color: '#4b5563'}}>
                Category indicates seat type, not a separate merit rank. Closing rank shown is for selected category in the final counselling round.
              </div>
            </div>
          )}
          <div style={{overflowX:'auto', width:'100%'}}>
          <table className="rank-finder-table" style={{minWidth:'1200px'}}>
            <thead>
              <tr>
                <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>College</th>
                {!isYear2024View && <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>City</th>}
                {!isYear2024View && <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Type</th>}
                <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Program</th>
                <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Category</th>
                {!isYear2024View && <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Status</th>}
                <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Closing Rank</th>
                {!isYear2024View && <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Competition</th>}
              </tr>
            </thead>
            <tbody>
              {visibleRows.length === 0 ? (
                <tr><td colSpan={isYear2024View ? 4 : 8} style={{textAlign:'center',padding:'1rem'}}>No results found. Try adjusting your search criteria.</td></tr>
              ) : visibleRows.map((r,i)=> (
                <tr key={i} style={{
                  background: i % 2 === 0 ? '#ffffff' : '#f8fafc',
                  borderBottom: '1px solid #e5e7eb',
                  transition: 'all 0.3s ease'
                }} onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'rgba(37, 99, 235, 0.05)';
                  e.currentTarget.style.transform = 'translateY(-2px)';
                  e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.1)';
                }} onMouseLeave={(e) => {
                  e.currentTarget.style.background = i % 2 === 0 ? '#ffffff' : '#f8fafc';
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = 'none';
                }}>
                  <td className="college-name" style={{padding:'12px', fontSize:'13px', color:'#1f2937', background:'transparent'}}>
                    <div>
                      <a href={`college_detail.php?id=${r.college_id}`} target="_blank" style={{color:'#1f2937', textDecoration:'none', fontWeight:'600'}}>{r.college}</a>
                      {!isYear2024View && r.college_code && <div style={{fontSize:'11px',color:'#718096', marginTop:'2px'}}>{r.college_code}</div>}
                    </div>
                  </td>
                  {!isYear2024View && <td style={{padding:'12px', fontSize:'13px', color:'#1f2937', background:'transparent'}}>{r.city || '—'}</td>}
                  {!isYear2024View && <td style={{padding:'12px', background:'transparent'}}>
                    <span style={{
                      padding:'4px 8px',
                      borderRadius:'12px',
                      fontSize:'11px',
                      fontWeight:'500',
                      background: (r.inst_type === 'GOVT' || r.inst_type === 'Government') ? 'rgba(59, 130, 246, 0.1)' : 
                                  (r.inst_type === 'Self-Fin' || r.inst_type === 'Private') ? 'rgba(245, 158, 11, 0.1)' : 
                                  r.inst_type === 'GIA' ? 'rgba(139, 92, 246, 0.1)' : 'rgba(107, 114, 128, 0.1)',
                      color: (r.inst_type === 'GOVT' || r.inst_type === 'Government') ? '#1e40af' : 
                             (r.inst_type === 'Self-Fin' || r.inst_type === 'Private') ? '#92400e' : 
                             r.inst_type === 'GIA' ? '#6b21a8' : '#374151',
                      border: '1px solid rgba(0,0,0,0.1)'
                    }}>
                      {r.inst_type || '—'}
                    </span>
                  </td>}
                  <td style={{padding:'12px', fontSize:'13px', color:'#1f2937', background:'transparent'}}>
                    <div>
                      <div style={{fontWeight:'600', color:'#1f2937'}}>{r.course}</div>
                      {!isYear2024View && r.duration_formatted && <div style={{fontSize:'11px',color:'#6b7280', marginTop:'2px'}}>{r.duration_formatted}</div>}
                    </div>
                  </td>
                  <td style={{padding:'12px', fontSize:'13px', color:'#1f2937', background:'transparent'}}>{normalizeCategoryDisplay(r.category)}</td>
                  {!isYear2024View && <td style={{padding:'12px', background:'transparent'}}>
                    <span style={{
                      display:'inline-block',
                      padding:'6px 12px',
                      borderRadius:'20px',
                      background: r.status === 'High Chance' ? 'rgba(16, 185, 129, 0.1)' : 
                                  r.status === 'Eligible' ? 'rgba(59, 130, 246, 0.1)' : 
                                  r.status === 'Waitlist' ? 'rgba(245, 158, 11, 0.1)' : 
                                  r.status === 'Borderline' ? 'rgba(249, 115, 22, 0.1)' : 'rgba(107, 114, 128, 0.1)',
                      color: r.status === 'High Chance' ? '#10b981' : 
                             r.status === 'Eligible' ? '#3b82f6' : 
                             r.status === 'Waitlist' ? '#f59e0b' : 
                             r.status === 'Borderline' ? '#f97316' : '#6b7280',
                      fontSize:'12px',
                      fontWeight:'600',
                      border: '1px solid rgba(0,0,0,0.1)'
                    }}>
                      {r.status || 'Eligible'}
                    </span>
                  </td>}
                  <td style={{padding:'12px', fontSize:'13px', color:'#1f2937', fontWeight:'500', background:'transparent'}}>{formatRank(r.closing_rank, r.closing_rank_formatted)}</td>
                  {!isYear2024View && (
                  <td style={{padding:'12px', background:'transparent'}}>
                    {(() => {
                      // Calculate competition level based on difference between user rank and closing rank
                      const userRank = parseInt(String(rank || '').trim(), 10);
                      const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
                      const closingRank = parseInt(closingRankStr, 10);
                      
                      let competitionLevel = '—';
                      let bgColor = 'rgba(107, 114, 128, 0.1)';
                      let textColor = '#6b7280';
                      
                      // Only calculate if we have both user rank and closing rank
                      if (!isNaN(userRank) && userRank > 0 && !isNaN(closingRank) && closingRank > 0) {
                        // Calculate the difference between closing rank and user rank
                        const rankDifference = closingRank - userRank;
                        
                        // Calculate percentage difference: (difference / user_rank) * 100
                        const percentageDifference = (rankDifference / userRank) * 100;
                        
                        // If difference is small (user rank is close to closing rank) → High competition
                        // If difference is large (user rank is much better than closing rank) → Medium competition
                        // Threshold: If difference is less than 50% of user rank, it's High competition
                        if (percentageDifference <= 50) {
                          // Small difference - user rank is close to closing rank → High competition
                          competitionLevel = 'High';
                          bgColor = 'rgba(217, 119, 6, 0.1)';
                          textColor = '#d97706';
                        } else {
                          // Large difference - user rank is much better than closing rank → Medium competition
                          competitionLevel = 'Medium';
                          bgColor = 'rgba(37, 99, 235, 0.1)';
                          textColor = '#2563eb';
                        }
                      } else if (!isNaN(closingRank) && closingRank > 0) {
                        // If no user rank provided, default to Medium competition
                        competitionLevel = 'Medium';
                        bgColor = 'rgba(37, 99, 235, 0.1)';
                        textColor = '#2563eb';
                      }
                      
                      return (
                        <span style={{
                          padding:'6px 10px',
                          borderRadius:'15px',
                          fontSize:'11px',
                          fontWeight:'600',
                          background: bgColor,
                          color: textColor,
                          border: '1px solid rgba(0,0,0,0.1)'
                        }}>
                          {competitionLevel}
                        </span>
                      );
                    })()}
                  </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>
        );
      })()}
      {((rank && parseInt(String(rank || '').trim(), 10) > 0) || (parseInt(String(year || '').trim(), 10) === 2024)) && rows.length > 0 && (
        <div className="pagination-container">
          <div>
            <strong style={{fontSize:'1.1rem', color:'var(--dark)'}}>{total.toLocaleString()}</strong>
            <span style={{marginLeft:'0.5rem',color:'var(--gray)',fontSize:'0.95rem'}}>results found</span>
            {metadata && (
              <span style={{marginLeft:'1rem',color:'var(--gray)',fontSize:'0.9rem', fontStyle:'italic'}}>
                (Comprehensive search with all data sources)
              </span>
            )}
          </div>
          <div className="pagination-buttons">
            <button className="btn" onClick={()=>setPage(1)} disabled={page===1}>« First</button>
            <button className="btn" onClick={()=>setPage(p=>Math.max(1, p-1))} disabled={page===1}>‹ Prev</button>
            <button className="btn" onClick={()=>setPage(p=>Math.min(totalPages, p+1))} disabled={page===totalPages}>Next ›</button>
            <button className="btn" onClick={()=>setPage(totalPages)} disabled={page===totalPages}>Last »</button>
          </div>
        </div>
      )}
      {error && <div className="error-message" style={{marginTop:'1rem'}}>{error}</div>}

      {/* Eligibility Status Message - Only show if rank is entered (not for year 2024 view without rank) */}
      {rows.length > 0 && rank && parseInt(String(rank || '').trim(), 10) > 0 && (() => {
        const userRank = parseInt(String(rank || '').trim(), 10);
        
        // Check if there are any rows with valid closing ranks (not placeholder rows)
        const rowsWithValidClosingRank = rows.filter(r => {
          const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
          const closingRank = parseInt(closingRankStr, 10);
          return !isNaN(closingRank) && closingRank > 0;
        });
        
        // Only show eligibility message if there are rows with valid closing ranks
        // If all rows are placeholder rows (no valid closing_rank), don't show the message
        if (rowsWithValidClosingRank.length === 0) {
          return null;
        }
        
        const eligibleColleges = rowsWithValidClosingRank.filter(r => {
          // Handle both formatted and unformatted closing ranks
          const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
          const closingRank = parseInt(closingRankStr, 10);
          // User is eligible if their rank is less than or equal to closing rank (lower rank number is better)
          return !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
        });
        const isEligible = eligibleColleges.length > 0;
        const totalColleges = rowsWithValidClosingRank.length;
        const eligibilityPercentage = totalColleges > 0 ? Math.round((eligibleColleges.length / totalColleges) * 100) : 0;
        
        return (
          <div className="eligibility-message" style={{
            marginTop: '1.5rem',
            marginBottom: '1rem',
            padding: '20px',
            borderRadius: '12px',
            background: isEligible 
              ? 'linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%)' 
              : 'linear-gradient(135deg, #fee2e2 0%, #fecaca 100%)',
            border: `2px solid ${isEligible ? '#10b981' : '#ef4444'}`,
            boxShadow: `0 4px 20px ${isEligible ? 'rgba(16, 185, 129, 0.2)' : 'rgba(239, 68, 68, 0.2)'}`,
            animation: 'fadeIn 0.5s ease-in',
            maxWidth: '1400px',
            marginLeft: 'auto',
            marginRight: 'auto'
          }}>
            <div style={{display: 'flex', alignItems: 'center', gap: '15px', flexWrap: 'wrap'}}>
              <div style={{
                fontSize: '48px',
                lineHeight: '1'
              }}>
                {isEligible ? '✅' : '❌'}
              </div>
              <div style={{flex: '1', minWidth: '250px'}}>
                <h3 style={{
                  margin: '0 0 8px 0',
                  fontSize: '20px',
                  fontWeight: '700',
                  color: isEligible ? '#065f46' : '#991b1b'
                }}>
                  {isEligible 
                    ? `Congratulations! You are Eligible for Admission` 
                    : `Sorry, You are Not Eligible for Admission`}
                </h3>
                <div style={{
                  fontSize: '15px',
                  color: isEligible ? '#047857' : '#dc2626',
                  lineHeight: '1.6',
                  marginTop: '8px'
                }}>
                  {isEligible ? (
                    <>
                      <strong>Great news!</strong> Based on your rank <strong>{userRank.toLocaleString()}</strong>, you are eligible for admission in <strong>{eligibleColleges.length}</strong> out of <strong>{totalColleges}</strong> colleges/programs ({eligibilityPercentage}%).
                      {eligibleColleges.length > 0 && (
                        <div style={{marginTop: '10px', fontSize: '14px'}}>
                          You have a <strong>{eligibilityPercentage}%</strong> chance of getting admission based on the current search results.
                        </div>
                      )}
                    </>
                  ) : (
                    <>
                      <strong>Unfortunately,</strong> based on your rank <strong>{userRank.toLocaleString()}</strong>, you are not eligible for admission in any of the <strong>{totalColleges}</strong> colleges/programs shown in the current search results.
                      <div style={{marginTop: '10px', fontSize: '14px'}}>
                        <strong>Suggestions:</strong>
                        <ul style={{margin: '8px 0 0 20px', padding: 0}}>
                          <li>Try adjusting your search filters (category, city, program type)</li>
                          <li>Consider colleges in different cities or with different fee ranges</li>
                          <li>Check if there are other rounds or admission processes available</li>
                          <li>Review the closing ranks in the results to see what rank range is needed</li>
                        </ul>
                      </div>
                    </>
                  )}
                </div>
              </div>
              {isEligible && eligibleColleges.length > 0 && (
                <div style={{
                  textAlign: 'center',
                  padding: '15px 20px',
                  background: 'rgba(255, 255, 255, 0.6)',
                  borderRadius: '10px',
                  minWidth: '120px'
                }}>
                  <div style={{
                    fontSize: '32px',
                    fontWeight: '700',
                    color: '#10b981',
                    lineHeight: '1'
                  }}>
                    {eligibleColleges.length}
                  </div>
                  <div style={{
                    fontSize: '12px',
                    color: '#047857',
                    marginTop: '5px',
                    fontWeight: '600'
                  }}>
                    Eligible Options
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })()}

      {/* Results Section - Only show if rank is entered */}
      {((rank && parseInt(String(rank || '').trim(), 10) > 0) || (parseInt(String(year || '').trim(), 10) === 2024)) && (
      <div className="courses-card" style={{marginTop:'1rem'}}>
        <div className="courses-header" style={{display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:'1rem'}}>
          <h3>Results</h3>
          <div style={{display:'flex',gap:'12px',alignItems:'center',flexWrap:'wrap'}}>
            {/* Analytics Section */}
            {showAnalytics && rows.length > 0 && (
              <div style={{
                background: 'linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)',
                padding: '15px',
                borderRadius: '10px',
                border: '1px solid #2196f3',
                marginBottom: '15px',
                width: '100%'
              }}>
                <h4 style={{margin: '0 0 10px 0', color: '#1976d2', fontSize: '16px'}}>📊 Admission Analytics</h4>
                <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '10px'}}>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: '24px', fontWeight: 'bold', color: '#1976d2'}}>
                      {(() => {
                        const userRank = parseInt(String(rank || '').trim(), 10);
                        if (isNaN(userRank) || userRank <= 0) return '—';
                        const eligible = rows.filter(r => {
                          const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
                          const closingRank = parseInt(closingRankStr, 10);
                          return !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
                        });
                        return rows.length > 0 ? Math.round((eligible.length / rows.length) * 100) : 0;
                      })()}%
                    </div>
                    <div style={{fontSize: '12px', color: '#666'}}>Admission Probability</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: '24px', fontWeight: 'bold', color: '#4caf50'}}>
                      {(() => {
                        const userRank = parseInt(String(rank || '').trim(), 10);
                        if (isNaN(userRank) || userRank <= 0) return 0;
                        return rows.filter(r => {
                          const closingRankStr = String(r.closing_rank || r.closing_rank_formatted || '').replace(/[,\s]/g, '');
                          const closingRank = parseInt(closingRankStr, 10);
                          return !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
                        }).length;
                      })()}
                    </div>
                    <div style={{fontSize: '12px', color: '#666'}}>Eligible Colleges</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: '24px', fontWeight: 'bold', color: '#ff9800'}}>
                      ₹{Math.round(rows.reduce((sum, r) => sum + (r.fee_inr || 0), 0) / rows.length).toLocaleString()}
                    </div>
                    <div style={{fontSize: '12px', color: '#666'}}>Avg Fee</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: '24px', fontWeight: 'bold', color: '#9c27b0'}}>
                      {(() => {
                        const validRanks = rows.filter(r => {
                          const rank = r.closing_rank || r.closing_rank_formatted;
                          if (!rank || rank === 0 || rank === '0') return false;
                          const rankNum = typeof rank === 'string' ? parseInt(rank.replace(/[,\s]/g, ''), 10) : rank;
                          return !isNaN(rankNum) && rankNum > 0;
                        });
                        if (validRanks.length === 0) return '—';
                        const sum = validRanks.reduce((s, r) => {
                          const rank = r.closing_rank || r.closing_rank_formatted;
                          const rankNum = typeof rank === 'string' ? parseInt(String(rank).replace(/[,\s]/g, ''), 10) : rank;
                          return s + (rankNum || 0);
                        }, 0);
                        return Math.round(sum / validRanks.length).toLocaleString();
                      })()}
                    </div>
                    <div style={{fontSize: '12px', color: '#666'}}>Avg Closing Rank</div>
                  </div>
                </div>
              </div>
            )}
            
            {/* Comparison Tool Section */}
            {rows.length > 0 && (
              <div style={{
                background: 'linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%)',
                padding: '15px',
                borderRadius: '10px',
                border: '1px solid #9c27b0',
                marginBottom: '15px'
              }}>
                <h4 style={{margin: '0 0 10px 0', color: '#7b1fa2', fontSize: '16px'}}>🔍 College Comparison Tool</h4>
                <div style={{display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap'}}>
                  <span style={{fontSize: '14px', color: '#666'}}>Select colleges to compare:</span>
                  <div style={{display: 'flex', gap: '5px', flexWrap: 'wrap'}}>
                    {rows.slice(0, 5).map((row, index) => (
                      <button
                        key={index}
                        onClick={() => {
                          const isSelected = comparisonColleges.some(c => c.college_id === row.college_id);
                          if (isSelected) {
                            setComparisonColleges(comparisonColleges.filter(c => c.college_id !== row.college_id));
                          } else if (comparisonColleges.length < 3) {
                            setComparisonColleges([...comparisonColleges, row]);
                          }
                        }}
                        style={{
                          background: comparisonColleges.some(c => c.college_id === row.college_id) 
                            ? 'linear-gradient(135deg, #9c27b0 0%, #7b1fa2 100%)' 
                            : 'linear-gradient(135deg, #e1bee7 0%, #ce93d8 100%)',
                          color: comparisonColleges.some(c => c.college_id === row.college_id) ? 'white' : '#7b1fa2',
                          border: 'none',
                          padding: '6px 12px',
                          borderRadius: '6px',
                          fontSize: '12px',
                          cursor: 'pointer',
                          fontWeight: '500'
                        }}
                      >
                        {row.college.length > 20 ? row.college.substring(0, 20) + '...' : row.college}
                      </button>
                    ))}
                  </div>
                  {comparisonColleges.length > 0 && (
                    <button
                      onClick={() => setShowComparison(!showComparison)}
                      style={{
                        background: 'linear-gradient(135deg, #9c27b0 0%, #7b1fa2 100%)',
                        color: 'white',
                        border: 'none',
                        padding: '8px 16px',
                        borderRadius: '6px',
                        fontSize: '12px',
                        cursor: 'pointer',
                        fontWeight: '500'
                      }}
                    >
                      {showComparison ? 'Hide Comparison' : `Compare ${comparisonColleges.length} Colleges`}
                    </button>
                  )}
                </div>
                
                {/* Comparison Table */}
                {showComparison && comparisonColleges.length > 0 && (
                  <div style={{marginTop: '15px'}}>
                    <table style={{
                      width: '100%',
                      borderCollapse: 'collapse',
                      background: 'rgba(255,255,255,0.9)',
                      borderRadius: '8px',
                      overflow: 'hidden',
                      boxShadow: '0 2px 10px rgba(0,0,0,0.1)'
                    }}>
                      <thead>
                        <tr style={{background: 'linear-gradient(135deg, #9c27b0 0%, #7b1fa2 100%)', color: 'white'}}>
                          <th style={{padding: '10px', textAlign: 'left'}}>College</th>
                          <th style={{padding: '10px', textAlign: 'left'}}>Course</th>
                          <th style={{padding: '10px', textAlign: 'center'}}>Fee</th>
                          <th style={{padding: '10px', textAlign: 'center'}}>Closing Rank</th>
                          <th style={{padding: '10px', textAlign: 'center'}}>Competition</th>
                          <th style={{padding: '10px', textAlign: 'center'}}>Chance</th>
                        </tr>
                      </thead>
                      <tbody>
                        {comparisonColleges.map((college, index) => (
                          <tr key={index} style={{borderBottom: '1px solid #e0e0e0'}}>
                            <td style={{padding: '10px', fontWeight: '500'}}>{college.college}</td>
                            <td style={{padding: '10px'}}>{college.course}</td>
                            <td style={{padding: '10px', textAlign: 'center'}}>₹{college.fee_inr?.toLocaleString() || 'N/A'}</td>
                            <td style={{padding: '10px', textAlign: 'center', fontWeight: '500'}}>
                              {college.closing_rank && college.closing_rank > 0 ? college.closing_rank.toLocaleString() : '—'}
                            </td>
                            <td style={{padding: '10px', textAlign: 'center'}}>
                              {(() => {
                                // Calculate competition based on difference between user rank and closing rank
                                const userRank = parseInt(String(rank || '').trim(), 10);
                                const closingRank = college.closing_rank ? parseInt(String(college.closing_rank).replace(/[,\s]/g, ''), 10) : 0;
                                
                                let competitionLevel = '—';
                                let bgColor = '#e3f2fd';
                                let textColor = '#1565c0';
                                
                                if (!isNaN(userRank) && userRank > 0 && !isNaN(closingRank) && closingRank > 0) {
                                  const rankDifference = closingRank - userRank;
                                  const percentageDifference = (rankDifference / userRank) * 100;
                                  
                                  if (percentageDifference <= 50) {
                                    competitionLevel = 'High';
                                    bgColor = '#fff3e0';
                                    textColor = '#ef6c00';
                                  } else {
                                    competitionLevel = 'Medium';
                                    bgColor = '#e8f5e8';
                                    textColor = '#2e7d32';
                                  }
                                } else if (!isNaN(closingRank) && closingRank > 0) {
                                  competitionLevel = 'High';
                                  bgColor = '#e8f5e8';
                                  textColor = '#2e7d32';
                                }
                                
                                return (
                                  <span style={{
                                    padding: '4px 8px',
                                    borderRadius: '4px',
                                    fontSize: '11px',
                                    fontWeight: '500',
                                    background: bgColor,
                                    color: textColor
                                  }}>
                                    {competitionLevel}
                                  </span>
                                );
                              })()}
                            </td>
                            <td style={{padding: '10px', textAlign: 'center'}}>
                              <span style={{
                                padding: '4px 8px',
                                borderRadius: '4px',
                                fontSize: '11px',
                                fontWeight: '500',
                                background: (() => {
                                  const userRank = parseInt(String(rank || '').trim(), 10);
                                  if (isNaN(userRank) || userRank <= 0) return '#ffebee';
                                  const closingRankStr = String(college.closing_rank || '').replace(/[,\s]/g, '');
                                  const closingRank = parseInt(closingRankStr, 10);
                                  const isEligible = !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
                                  return isEligible ? '#e8f5e8' : '#ffebee';
                                })(),
                                color: (() => {
                                  const userRank = parseInt(String(rank || '').trim(), 10);
                                  if (isNaN(userRank) || userRank <= 0) return '#c62828';
                                  const closingRankStr = String(college.closing_rank || '').replace(/[,\s]/g, '');
                                  const closingRank = parseInt(closingRankStr, 10);
                                  const isEligible = !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
                                  return isEligible ? '#2e7d32' : '#c62828';
                                })()
                              }}>
                                {(() => {
                                  const userRank = parseInt(String(rank || '').trim(), 10);
                                  if (isNaN(userRank) || userRank <= 0) return '❌ Not Eligible';
                                  const closingRankStr = String(college.closing_rank || '').replace(/[,\s]/g, '');
                                  const closingRank = parseInt(closingRankStr, 10);
                                  const isEligible = !isNaN(closingRank) && closingRank > 0 && userRank <= closingRank;
                                  return isEligible ? '✅ Eligible' : '❌ Not Eligible';
                                })()}
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}
            
            {/* Download Options */}
            {rows.length > 0 && (
              <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
                <button 
                  onClick={()=>downloadStudentListPdf()}
                  style={{fontSize:'12px',padding:'6px 12px',background:'#dc3545',color:'white',border:'none',borderRadius:'4px',cursor:'pointer'}}
                  title="Download Student List PDF"
                >
                  📄 Student List
                </button>
              </div>
            )}
            {/* Pagination Controls */}
            <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
              <label style={{fontSize:'12px',color:'#666'}}>Rows:</label>
              <select value={pageSize} onChange={e=>setPageSize(parseInt(e.target.value,10) || 10)} style={{fontSize:'12px',padding:'4px 8px'}}>
                {[10,25,50,100].map(n => <option key={n} value={n}>{n}</option>)}
              </select>
              <div style={{fontSize:'12px',color:'#666'}}>Page {page} of {totalPages}</div>
            </div>
          </div>
        </div>
        
        {/* Metadata Display */}
        {metadata && (
          <div style={{background:'#f8fafc',padding:'1rem',marginBottom:'1rem',borderRadius:'8px',fontSize:'14px'}}>
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(200px, 1fr))',gap:'1rem'}}>
              <div>
                <strong>Search Results:</strong> {metadata.total || metadata.total_results} unique college-course combinations
                {metadata.original_total && metadata.original_total > (metadata.total || metadata.total_results) && (
                  <span style={{color:'#6b7280',fontSize:'12px',marginLeft:'8px'}}>
                    (deduplicated from {metadata.original_total} total records)
                  </span>
                )}
              </div>
              <div>
                <strong>Generated:</strong> {metadata.generated_at}
              </div>
            </div>
            
            {/* Analytics Display */}
            {metadata.analytics && (
              <div style={{marginTop:'1rem',padding:'1rem',background:'white',borderRadius:'6px',border:'1px solid #e5e7eb'}}>
                <h4 style={{margin:'0 0 0.5rem 0',fontSize:'16px',color:'#374151'}}>Search Analytics</h4>
                <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(150px, 1fr))',gap:'1rem'}}>
                  <div>
                    <div style={{fontSize:'12px',color:'#6b7280'}}>Admission Status</div>
                    <div style={{fontSize:'14px',fontWeight:'500'}}>
                      {metadata.analytics.high_chance_count} High Chance, {metadata.analytics.eligible_count} Eligible
                    </div>
                  </div>
                  <div>
                    <div style={{fontSize:'12px',color:'#6b7280'}}>Avg. Probability</div>
                    <div style={{fontSize:'14px',fontWeight:'500',color:metadata.analytics.avg_admission_probability > 70 ? '#10b981' : metadata.analytics.avg_admission_probability > 40 ? '#f59e0b' : '#ef4444'}}>
                      {metadata.analytics.avg_admission_probability}%
                    </div>
                  </div>
                  <div>
                    <div style={{fontSize:'12px',color:'#6b7280'}}>Search Quality</div>
                    <div style={{fontSize:'14px',fontWeight:'500',color:metadata.analytics.search_effectiveness === 'Good' ? '#10b981' : '#f59e0b'}}>
                      {metadata.analytics.search_effectiveness}
                    </div>
                  </div>
                  {metadata.analytics.top_colleges && metadata.analytics.top_colleges.length > 0 && (
                    <div>
                      <div style={{fontSize:'12px',color:'#6b7280'}}>Top Colleges</div>
                      <div style={{fontSize:'12px',color:'#374151'}}>
                        {metadata.analytics.top_colleges.slice(0, 3).join(', ')}
                        {metadata.analytics.top_colleges.length > 3 && '...'}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
      )}

      {/* Show message if rank is not entered AND user has attempted to search */}
      {hasAttemptedSearch && (!rank || parseInt(String(rank || '').trim(), 10) <= 0) && !(parseInt(String(year || '').trim(), 10) === 2024) && (
        <div style={{
          marginTop: '2rem',
          padding: '2rem',
          textAlign: 'center',
          background: 'linear-gradient(135deg, #fef3c7 0%, #fde68a 100%)',
          borderRadius: '12px',
          border: '2px solid #f59e0b',
          boxShadow: '0 4px 20px rgba(245, 158, 11, 0.2)'
        }}>
          <div style={{fontSize: '48px', marginBottom: '1rem'}}>🔍</div>
          <h3 style={{margin: '0 0 0.5rem 0', fontSize: '20px', fontWeight: '700', color: '#92400e'}}>
            Rank is Required
          </h3>
          <p style={{margin: '0', fontSize: '15px', color: '#78350f', lineHeight: '1.6'}}>
            Please enter your rank in the search form above to view admission results.
          </p>
        </div>
      )}

      {/* View All Notifications Modal */}
      {showAllNotifications && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          background: 'rgba(0, 0, 0, 0.7)',
          zIndex: 10000,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          padding: '20px'
        }} onClick={() => setShowAllNotifications(false)}>
          <div style={{
            background: 'white',
            borderRadius: '16px',
            maxWidth: '900px',
            width: '100%',
            maxHeight: '90vh',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            boxShadow: '0 20px 60px rgba(0,0,0,0.3)'
          }} onClick={(e) => e.stopPropagation()}>
            <div style={{
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              padding: '20px 24px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              color: 'white'
            }}>
              <h3 style={{margin: 0, fontSize: '22px', fontWeight: '700'}}>
                <i className="fas fa-bell me-2"></i>
                All Notifications ({notifications.length})
              </h3>
              <button
                onClick={() => setShowAllNotifications(false)}
                style={{
                  background: 'rgba(255,255,255,0.2)',
                  border: 'none',
                  color: 'white',
                  fontSize: '28px',
                  width: '40px',
                  height: '40px',
                  borderRadius: '50%',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'all 0.3s ease'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'rgba(255,255,255,0.3)';
                  e.currentTarget.style.transform = 'scale(1.1)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'rgba(255,255,255,0.2)';
                  e.currentTarget.style.transform = 'scale(1)';
                }}
              >
                ×
              </button>
            </div>
            <div style={{
              padding: '24px',
              overflowY: 'auto',
              maxHeight: 'calc(90vh - 100px)'
            }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                gap: '16px'
              }}>
                {notifications.map((n, i) => (
                  <div
                    key={i}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setShowAllNotifications(false);
                      // Use the same logic as above to open notification
                      try {
                        if (typeof openNotificationBrochure === 'function') {
                          openNotificationBrochure(n, i);
                        } else {
                          const modal = document.getElementById('brochureModal');
                          const modalTitle = document.getElementById('brochureModalTitle');
                          if (modal && modalTitle) {
                            modalTitle.innerHTML = `<i className="fas fa-file-pdf me-2"></i>${n.title || 'Notification'}`;
                            if (typeof loadBrochureContent === 'function') {
                              loadBrochureContent(n, i);
                            } else {
                              const modalContent = document.getElementById('brochureContent');
                              const downloadLink = document.getElementById('brochureDownloadLink');
                              if (modalContent) {
                                if (n.brochure_file) {
                                  modalContent.innerHTML = `
                                    <div className="brochure-pdf-container">
                                      <iframe 
                                        src="${n.brochure_file}" 
                                        width="100%" 
                                        height="500px"
                                        style="border: none; border-radius: 8px;"
                                        title="${n.title}">
                                      </iframe>
                                    </div>
                                  `;
                                  if (downloadLink) {
                                    downloadLink.href = n.brochure_file;
                                    downloadLink.style.display = 'inline-block';
                                  }
                                } else {
                                  modalContent.innerHTML = `
                                    <div className="brochure-info">
                                      <div className="brochure-header">
                                        <h4>${n.title || 'Notification'}</h4>
                                        <p className="brochure-date">
                                          <i className="fas fa-calendar-alt me-2"></i>${n.date || 'N/A'}
                                        </p>
                                      </div>
                                      <div className="brochure-description">
                                        <p>This notification contains important information regarding the admission process.</p>
                                        ${n.url && n.url !== '#' ? 
                                          `<p><strong>External Link:</strong> <a href="${n.url}" target="_blank" rel="noopener noreferrer">View Full Notification</a></p>` : 
                                          ''
                                        }
                                        ${n.brochure_title ? `<p><strong>Brochure:</strong> ${n.brochure_title}</p>` : ''}
                                      </div>
                                    </div>
                                  `;
                                  if (downloadLink) {
                                    downloadLink.style.display = 'none';
                                  }
                                }
                              }
                            }
                            modal.style.display = 'flex';
                          } else if (n.url && n.url !== '#') {
                            window.open(n.url, '_blank');
                          }
                        }
                      } catch (err) {
                        console.error('Error opening notification:', err);
                        if (n.url && n.url !== '#') {
                          window.open(n.url, '_blank');
                        }
                      }
                    }}
                    style={{
                      background: '#f9fafb',
                      borderRadius: '12px',
                      padding: '16px',
                      cursor: 'pointer',
                      transition: 'all 0.3s ease',
                      border: '1px solid #e5e7eb',
                      borderLeft: '4px solid #667eea'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.transform = 'translateY(-4px)';
                      e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.15)';
                      e.currentTarget.style.background = 'white';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.transform = 'translateY(0)';
                      e.currentTarget.style.boxShadow = 'none';
                      e.currentTarget.style.background = '#f9fafb';
                    }}
                  >
                    <div style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                      marginBottom: '12px',
                      fontSize: '12px',
                      color: '#667eea',
                      fontWeight: '600'
                    }}>
                      <i className="fas fa-calendar-alt"></i>
                      <span>{n.date || 'N/A'}</span>
                    </div>
                    <div style={{
                      fontSize: '16px',
                      fontWeight: '600',
                      color: '#1f2937',
                      marginBottom: '8px',
                      lineHeight: '1.4'
                    }}>
                      {n.title || 'Notification'}
                    </div>
                    {n.url && n.url !== '#' && (
                      <div style={{
                        fontSize: '12px',
                        color: '#6b7280',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                        marginTop: '8px'
                      }}>
                        <i className="fas fa-external-link-alt" style={{color: '#667eea'}}></i>
                        <span>Has external link</span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}


      {/* College-wise Cutoff Section */}
      <div className="college-cutoff-section" style={{
        marginTop:'2rem',
        marginBottom: '2rem',
        background: 'linear-gradient(135deg, rgba(255,255,255,0.1), rgba(255,255,255,0.05))',
        backdropFilter: 'blur(10px)',
        borderRadius: '20px',
        border: '1px solid rgba(255,255,255,0.2)',
        boxShadow: '0 8px 32px rgba(0,0,0,0.1), inset 0 1px 0 rgba(255,255,255,0.2)',
        padding: '20px',
        maxWidth: '1400px',
        marginLeft: 'auto',
        marginRight: 'auto'
      }}>
        <h3 style={{
          textAlign:'center',
          marginBottom:'20px',
          color:'#2d3748',
          fontSize:'24px',
          fontWeight:'600',
          textShadow: '0 1px 2px rgba(0,0,0,0.1)'
        }}>
          🏛️ College-wise Cutoff Analysis
        </h3>
        
        <div className="college-selection" style={{marginBottom:'20px'}}>
          <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px'}}>
            <label style={{fontWeight:'500', color:'#4a5568', margin: 0}}>
              Select Colleges (up to 5) to view program-wise cutoffs:
            </label>
            <button
              onClick={async () => {
                try {
                  const response = await fetch('api/colleges.php?t=' + Date.now());
                  if (response.ok) {
                    const data = await safeJsonParse(response);
                    if (data && Array.isArray(data.all_colleges)) {
                      setAllColleges(data.all_colleges);
                    }
                  }
                } catch (error) {
                  console.error('Failed to refresh colleges:', error);
                }
              }}
              style={{
                padding: '4px 8px',
                fontSize: '12px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                transition: 'all 0.2s ease'
              }}
              onMouseEnter={(e) => {
                e.target.style.transform = 'scale(1.05)';
                e.target.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
              }}
              onMouseLeave={(e) => {
                e.target.style.transform = 'scale(1)';
                e.target.style.boxShadow = 'none';
              }}
            >
              🔄 Refresh Colleges
            </button>
          </div>
          
          {/* Helpful message */}
          {rows.length === 0 && allColleges.length > 0 && (
            <div style={{
              background: 'linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(147, 51, 234, 0.1))',
              border: '1px solid rgba(59, 130, 246, 0.2)',
              borderRadius: '8px',
              padding: '12px',
              marginBottom: '10px',
              fontSize: '14px',
              color: '#4a5568'
            }}>
              💡 <strong>Tip:</strong> Perform a search first to see colleges from your results, or select from all available colleges below.
            </div>
          )}
          
          {/* Selection counter */}
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '8px',
            fontSize: '14px',
            color: selectedColleges.length >= 5 ? '#dc3545' : '#6c757d'
          }}>
            <span>
              Selected: {selectedColleges.length}/5 colleges
            </span>
            {selectedColleges.length >= 5 && (
              <span style={{fontSize: '12px', fontWeight: 'bold'}}>
                ⚠️ Maximum reached
              </span>
            )}
          </div>
          
          <div style={{position:'relative'}}>
            {(() => {
              // Helper function to normalize college name for deduplication - more aggressive
              const normalizeCollegeName = (name) => {
                if (!name) return '';
                let normalized = name.trim()
                  .toUpperCase()
                  .replace(/\s+/g, ' ')
                  .trim();
                
                // Normalize common abbreviations and variations
                normalized = normalized.replace(/\bENGG\.?\b/g, 'ENGINEERING');
                normalized = normalized.replace(/\bTECH\.?\b/g, 'TECHNOLOGY');
                normalized = normalized.replace(/\bINST\.?\b/g, 'INSTITUTE');
                normalized = normalized.replace(/\bCOLL\.?\b/g, 'COLLEGE');
                normalized = normalized.replace(/\bUNIV\.?\b/g, 'UNIVERSITY');
                normalized = normalized.replace(/\b&/g, 'AND');
                normalized = normalized.replace(/\./g, ''); // Remove all dots
                normalized = normalized.replace(/\s+/g, ' ').trim();
                
                return normalized;
              };
              
              // Helper function to get base college name (first meaningful part)
              const getBaseCollegeName = (name) => {
                if (!name) return '';
                const normalized = normalizeCollegeName(name);
                // Get the first part before comma, dash, or parentheses (main college name)
                const base = normalized.split(/[,\-\(]/)[0].trim();
                // Remove common suffixes
                return base.replace(/\s+(UNIVERSITY|INSTITUTE|COLLEGE|TECHNOLOGY|TECH|ENGINEERING|ENGG)[,\s]*$/i, '').trim() || base;
              };
              
              // Helper function to get display name (main college name only, no branch/campus details)
              const getDisplayName = (name) => {
                if (!name) return '';
                // Remove everything after comma, dash, parentheses, or common branch indicators
                let display = name.split(/[,\(]/)[0].trim();
                // Remove common branch/faculty patterns (more aggressive)
                display = display.replace(/\s*-\s*(FACULTY|BRANCH|CAMPUS|DEPARTMENT|OF|FOR).*$/i, '');
                display = display.replace(/\s*\(.*$/i, '');
                // Remove contact info patterns (Contact No:, Email:, Website:)
                display = display.replace(/\s*(Contact No|Email|Website|Contact|Phone|Tel):.*$/i, '');
                // Remove address patterns (common address keywords)
                display = display.replace(/\s+(At|Near|Beside|Opposite|Behind|Road|Street|Avenue|Lane).*$/i, '');
                // Clean up extra spaces and trim
                display = display.replace(/\s+/g, ' ').trim();
                return display;
              };
              
              // Process search results first (priority), then allColleges
              const seenNormalizedNames = new Set(); // Track normalized display names (no spaces) we've seen
              const uniqueCollegesFromRows = []; // Colleges from search results
              const uniqueAllColleges = []; // Colleges from allColleges
              
              // First, process search results (they have priority)
              if (rows.length > 0) {
                rows.forEach(r => {
                  if (!r.college || selectedColleges.includes(r.college)) return;
                  
                  const fullName = r.college;
                  const displayName = getDisplayName(fullName);
                  if (!displayName || !displayName.trim()) return;
                  
                  // Normalize for comparison
                  const normalizedDisplay = normalizeCollegeName(displayName);
                  const normalizedNoSpaces = normalizedDisplay.replace(/\s+/g, '');
                  
                  // Add to seen set and to search results list
                  if (!seenNormalizedNames.has(normalizedNoSpaces)) {
                    seenNormalizedNames.add(normalizedNoSpaces);
                    uniqueCollegesFromRows.push({ 
                      source: 'search', 
                      college: r.college, 
                      college_id: r.college_id,
                      fullName: fullName, 
                      displayName: displayName 
                    });
                  }
                });
              }
              
              // Then, process allColleges (exclude those already in search results by normalized name)
              if (allColleges.length > 0) {
                allColleges.forEach(college => {
                  if (!college.name || selectedColleges.includes(college.name)) return;
                  
                  // Skip if exact match exists in search results
                  if (rows.length > 0 && rows.some(r => r.college === college.name)) return;
                  
                  const fullName = college.name;
                  const displayName = getDisplayName(fullName);
                  if (!displayName || !displayName.trim()) return;
                  
                  // Normalize for comparison
                  const normalizedDisplay = normalizeCollegeName(displayName);
                  const normalizedNoSpaces = normalizedDisplay.replace(/\s+/g, '');
                  
                  // Only add if not already seen (from search results)
                  if (!seenNormalizedNames.has(normalizedNoSpaces)) {
                    seenNormalizedNames.add(normalizedNoSpaces);
                    uniqueAllColleges.push({ 
                      source: 'all', 
                      college: college.name, 
                      college_id: college.id,
                      fullName: fullName, 
                      displayName: displayName 
                    });
                  }
                });
              }
              
              return (
                <select 
                  value="" 
                  disabled={selectedColleges.length >= 5}
                  onChange={e=>{
                    const value = e.target.value;
                    if (value && !selectedColleges.includes(value) && selectedColleges.length < 5) {
                      setSelectedColleges([...selectedColleges, value]);
                    }
                  }}
                  style={{
                    width:'100%', 
                    padding:'10px', 
                    borderRadius:'10px', 
                    border:'1px solid #e2e8f0', 
                    fontSize:'14px',
                    backgroundColor: selectedColleges.length >= 5 ? '#f8f9fa' : 'white',
                    color: selectedColleges.length >= 5 ? '#6c757d' : 'inherit',
                    cursor: selectedColleges.length >= 5 ? 'not-allowed' : 'pointer'
                  }}
                >
                  <option value="">
                    {selectedColleges.length >= 5 ? 'Maximum 5 colleges selected' : 'Select College to Add'}
                  </option>
                  
                  {/* Show colleges from search results first */}
                  {uniqueCollegesFromRows.length > 0 && (
                    <optgroup label="From Search Results">
                      {uniqueCollegesFromRows.map((r, idx) => {
                        const fullName = r.fullName || r.college;
                        const displayName = r.displayName || getDisplayName(fullName);
                        return (
                          <option key={`search-${r.college_id || idx}-${idx}`} value={fullName}>
                            {displayName}
                          </option>
                        );
                      })}
                    </optgroup>
                  )}
                  
                  {/* Show all available colleges */}
                  {uniqueAllColleges.length > 0 && (
                    <optgroup label={rows.length > 0 ? "All Available Colleges" : "Available Colleges"}>
                      {uniqueAllColleges.map((college, idx) => {
                        const fullName = college.fullName || college.name;
                        const displayName = college.displayName || getDisplayName(fullName);
                        return (
                          <option key={`all-${college.college_id || college.id || idx}`} value={fullName}>
                            {displayName}
                          </option>
                        );
                      })}
                    </optgroup>
                  )}
                  
                  {/* Loading state */}
                  {allColleges.length === 0 && rows.length === 0 && (
                    <option disabled>Loading colleges...</option>
                  )}
                </select>
              );
            })()}
            {selectedColleges.length > 0 && (
              <div style={{marginTop:'10px', display:'flex', flexWrap:'wrap', gap:'6px'}}>
                {selectedColleges.map((college, index) => (
                  <span key={index} style={{
                    background:'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                    color:'white',
                    padding:'6px 12px',
                    borderRadius:'15px',
                    fontSize:'13px',
                    display:'flex',
                    alignItems:'center',
                    gap:'6px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                  }}>
                    {college}
                    <button 
                      onClick={()=>setSelectedColleges(selectedColleges.filter((_,i)=>i!==index))}
                      style={{background:'rgba(255,255,255,0.2)', border:'none', color:'white', borderRadius:'50%', width:'18px', height:'18px', cursor:'pointer', fontSize:'12px'}}
                    >
                      ×
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>
          
          <div style={{marginTop:'15px', textAlign:'center'}}>
            <button 
              onClick={fetchCollegeCutoffs}
              disabled={selectedColleges.length === 0 || isLoadingCutoffs}
              style={{
                background: selectedColleges.length === 0 
                  ? 'linear-gradient(135deg, #6c757d 0%, #495057 100%)'
                  : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
                border: 'none',
                padding: '10px 20px',
                borderRadius: '10px',
                fontSize: '14px',
                fontWeight: '500',
                cursor: selectedColleges.length === 0 || isLoadingCutoffs ? 'not-allowed' : 'pointer',
                opacity: selectedColleges.length === 0 || isLoadingCutoffs ? 0.7 : 1,
                boxShadow: selectedColleges.length === 0 
                  ? '0 2px 8px rgba(108, 117, 125, 0.2)'
                  : '0 4px 15px rgba(102, 126, 234, 0.3)'
              }}
            >
              {isLoadingCutoffs 
                ? '⏳ Loading Cutoffs...' 
                : selectedColleges.length === 0 
                  ? '📊 Select Colleges First' 
                  : `📊 View Cutoffs (${selectedColleges.length} colleges)`
              }
            </button>
          </div>
        </div>
        
        {/* Debug Info */}
        {selectedColleges.length > 0 && (
          <div style={{marginTop:'10px', padding:'10px', background:'rgba(255,255,255,0.1)', borderRadius:'8px', fontSize:'12px'}}>
            <strong>Debug Info:</strong><br/>
            Selected Colleges: {selectedColleges.join(', ')}<br/>
            College Cutoffs Count: {collegeCutoffs.length}<br/>
            Loading: {isLoadingCutoffs ? 'Yes' : 'No'}
          </div>
        )}
        
        {/* College Cutoffs Results - Separate Sections for Each College */}
        {collegeCutoffs.length > 0 && (
          <div style={{marginTop:'20px'}}>
            {/* Enhanced Header with Controls */}
            <div style={{
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              padding: '20px',
              borderRadius: '15px',
              marginBottom: '20px',
              color: 'white',
              boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255,255,255,0.2)'
            }}>
              <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '15px'}}>
                <div>
                  <h3 style={{margin: '0 0 10px 0', fontSize: '24px', fontWeight: '600'}}>
                    🎓 College-wise Cutoff Analysis
                  </h3>
                  <p style={{margin: '0', opacity: 0.9, fontSize: '16px'}}>
                    {processCollegeCutoffs.totalPrograms} programs from {collegeCutoffs.length} college{collegeCutoffs.length > 1 ? 's' : ''}
                  </p>
                </div>
                
                {/* View Mode Toggle */}
                <div style={{display: 'flex', gap: '10px', alignItems: 'center'}}>
                  <div style={{display: 'flex', background: 'rgba(255,255,255,0.1)', borderRadius: '8px', padding: '4px'}}>
                    {['cards', 'table', 'compact'].map(mode => (
                      <button
                        key={mode}
                        onClick={() => setCutoffViewMode(mode)}
                        style={{
                          padding: '8px 12px',
                          borderRadius: '6px',
                          border: 'none',
                          background: cutoffViewMode === mode ? 'rgba(255,255,255,0.2)' : 'transparent',
                          color: 'white',
                          fontSize: '12px',
                          fontWeight: '500',
                          cursor: 'pointer',
                          transition: 'all 0.2s ease',
                          textTransform: 'capitalize'
                        }}
                      >
                        {mode === 'cards' ? '🎴 Cards' : mode === 'table' ? '📊 Table' : '📋 Compact'}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
              
              {/* Search and Sort Controls */}
              <div style={{marginTop: '15px', display: 'flex', gap: '15px', flexWrap: 'wrap', alignItems: 'center'}}>
                {/* Search */}
                <div style={{flex: '1', minWidth: '200px'}}>
                  <input
                    type="text"
                    placeholder="Search programs, colleges, categories..."
                    value={cutoffSearchTerm}
                    onChange={(e) => setCutoffSearchTerm(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '8px 12px',
                      borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)',
                      background: 'rgba(255,255,255,0.1)',
                      color: 'white',
                      fontSize: '14px'
                    }}
                  />
                </div>
                
                {/* Sort Controls */}
                <div style={{display: 'flex', gap: '10px', alignItems: 'center'}}>
                  <select
                    value={cutoffSortBy}
                    onChange={(e) => setCutoffSortBy(e.target.value)}
                    style={{
                      padding: '8px 12px',
                      borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)',
                      background: 'rgba(255,255,255,0.1)',
                      color: 'white',
                      fontSize: '14px'
                    }}
                  >
                    <option value="closing_rank">Closing Rank</option>
                    <option value="course_name">Course Name</option>
                    <option value="competition_level">Competition Level</option>
                  </select>
                  
                  <button
                    onClick={() => setCutoffSortOrder(cutoffSortOrder === 'asc' ? 'desc' : 'asc')}
                    style={{
                      padding: '8px 12px',
                      borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)',
                      background: 'rgba(255,255,255,0.1)',
                      color: 'white',
                      fontSize: '14px',
                      cursor: 'pointer'
                    }}
                  >
                    {cutoffSortOrder === 'asc' ? '↑' : '↓'}
                  </button>
                </div>
                
                {/* Page Size */}
                <div style={{display: 'flex', gap: '10px', alignItems: 'center'}}>
                  <span style={{fontSize: '14px', opacity: 0.9}}>Per page:</span>
                  <select
                    value={cutoffPageSize}
                    onChange={(e) => setCutoffPageSize(parseInt(e.target.value))}
                    style={{
                      padding: '8px 12px',
                      borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)',
                      background: 'rgba(255,255,255,0.1)',
                      color: 'white',
                      fontSize: '14px'
                    }}
                  >
                    <option value={6}>6</option>
                    <option value={12}>12</option>
                    <option value={24}>24</option>
                    <option value={48}>48</option>
                  </select>
                </div>
              </div>
            </div>
            
            {/* Pagination Info */}
            {processCollegeCutoffs.totalPages > 1 && (
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '15px',
                padding: '10px 15px',
                background: 'rgba(255,255,255,0.05)',
                borderRadius: '10px',
                border: '1px solid rgba(255,255,255,0.1)'
              }}>
                <div style={{color: '#6b7280', fontSize: '14px'}}>
                  Showing {((cutoffPage - 1) * cutoffPageSize) + 1} to {Math.min(cutoffPage * cutoffPageSize, processCollegeCutoffs.totalPrograms)} of {processCollegeCutoffs.totalPrograms} programs
                </div>
                
                <div style={{display: 'flex', gap: '5px'}}>
                  <button
                    onClick={() => setCutoffPage(Math.max(1, cutoffPage - 1))}
                    disabled={cutoffPage === 1}
                    style={{
                      padding: '6px 12px',
                      borderRadius: '6px',
                      border: '1px solid #ddd',
                      background: cutoffPage === 1 ? '#f5f5f5' : 'white',
                      color: cutoffPage === 1 ? '#999' : '#333',
                      cursor: cutoffPage === 1 ? 'not-allowed' : 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    ← Previous
                  </button>
                  
                  {Array.from({length: Math.min(5, processCollegeCutoffs.totalPages)}, (_, i) => {
                    const pageNum = Math.max(1, Math.min(processCollegeCutoffs.totalPages - 4, cutoffPage - 2)) + i;
                    return (
                      <button
                        key={pageNum}
                        onClick={() => setCutoffPage(pageNum)}
                        style={{
                          padding: '6px 12px',
                          borderRadius: '6px',
                          border: '1px solid #ddd',
                          background: cutoffPage === pageNum ? '#667eea' : 'white',
                          color: cutoffPage === pageNum ? 'white' : '#333',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        {pageNum}
                      </button>
                    );
                  })}
                  
                  <button
                    onClick={() => setCutoffPage(Math.min(processCollegeCutoffs.totalPages, cutoffPage + 1))}
                    disabled={cutoffPage === processCollegeCutoffs.totalPages}
                    style={{
                      padding: '6px 12px',
                      borderRadius: '6px',
                      border: '1px solid #ddd',
                      background: cutoffPage === processCollegeCutoffs.totalPages ? '#f5f5f5' : 'white',
                      color: cutoffPage === processCollegeCutoffs.totalPages ? '#999' : '#333',
                      cursor: cutoffPage === processCollegeCutoffs.totalPages ? 'not-allowed' : 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    Next →
                  </button>
                </div>
              </div>
            )}
            
            {/* Dynamic Content Based on View Mode */}
            {cutoffViewMode === 'cards' && (
              <div style={{display:'grid', gap:'25px'}}>
                {processCollegeCutoffs.processedColleges.map((college, collegeIndex) => (
                  <div key={collegeIndex} style={{
                    background: 'rgba(255,255,255,0.05)',
                    borderRadius: '20px',
                    border: '1px solid rgba(255,255,255,0.1)',
                    backdropFilter: 'blur(10px)',
                    overflow: 'hidden',
                    boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
                    transition: 'all 0.3s ease'
                  }}>
                    {/* College Header */}
                    <div style={{
                      background: `linear-gradient(135deg, 
                        hsl(${(collegeIndex * 137.5) % 360}, 70%, 60%) 0%, 
                        hsl(${((collegeIndex * 137.5) + 30) % 360}, 70%, 50%) 100%)`,
                      padding: '25px',
                      color: 'white',
                      textAlign: 'center',
                      position: 'relative',
                      overflow: 'hidden'
                    }}>
                      <div style={{
                        position: 'absolute',
                        top: '-50%',
                        left: '-50%',
                        width: '200%',
                        height: '200%',
                        background: 'radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%)',
                        animation: 'float 6s ease-in-out infinite'
                      }}></div>
                      <h4 style={{
                        fontSize: '20px',
                        fontWeight: '600',
                        margin: '0',
                        textShadow: '0 2px 4px rgba(0,0,0,0.3)',
                        position: 'relative',
                        zIndex: 1
                      }}>
                        🏛️ {college.college_name}
                      </h4>
                      <p style={{
                        fontSize: '14px',
                        margin: '8px 0 0 0',
                        opacity: 0.9,
                        position: 'relative',
                        zIndex: 1
                      }}>
                        {college.programs.length} program{college.programs.length > 1 ? 's' : ''} available
                      </p>
                    </div>
                    
                    {/* Programs Grid */}
                    <div style={{padding: '20px'}}>
                      <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
                        gap: '15px'
                      }}>
                        {college.programs.map((program, programIndex) => (
                          <div key={programIndex} style={{
                            background: 'rgba(255,255,255,0.05)',
                            padding: '16px',
                            borderRadius: '12px',
                            border: '1px solid rgba(255,255,255,0.1)',
                            transition: 'all 0.3s ease',
                            cursor: 'pointer'
                          }} 
                          onMouseEnter={(e) => {
                            e.currentTarget.style.background = 'rgba(255,255,255,0.1)';
                            e.currentTarget.style.transform = 'translateY(-2px)';
                            e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.1)';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                            e.currentTarget.style.transform = 'translateY(0)';
                            e.currentTarget.style.boxShadow = 'none';
                          }}>
                            <div style={{
                              fontWeight: '600',
                              color: '#2d3748',
                              marginBottom: '12px',
                              fontSize: '15px',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '8px'
                            }}>
                              <span style={{
                                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                color: 'white',
                                padding: '4px 8px',
                                borderRadius: '8px',
                                fontSize: '12px',
                                fontWeight: '500'
                              }}>
                                📚
                              </span>
                              {program.course_name}
                            </div>
                            
                            <div style={{
                              display: 'grid',
                              gridTemplateColumns: '1fr 1fr',
                              gap: '8px',
                              fontSize: '13px'
                            }}>
                              <div style={{
                                background: 'rgba(16, 185, 129, 0.1)',
                                padding: '8px',
                                borderRadius: '8px',
                                border: '1px solid rgba(16, 185, 129, 0.2)'
                              }}>
                                <div style={{color: '#6b7280', fontSize: '11px', marginBottom: '2px'}}>Open Rank</div>
                                <div style={{color: '#10b981', fontWeight: '600'}}>
                                  {formatRank(program.open_rank, program.open_rank_formatted)}
                                </div>
                              </div>
                              
                              <div style={{
                                background: 'rgba(245, 158, 11, 0.1)',
                                padding: '8px',
                                borderRadius: '8px',
                                border: '1px solid rgba(245, 158, 11, 0.2)'
                              }}>
                                <div style={{color: '#6b7280', fontSize: '11px', marginBottom: '2px'}}>Closing Rank</div>
                                <div style={{color: '#f59e0b', fontWeight: '600'}}>
                                  {formatRank(program.closing_rank, program.closing_rank_formatted)}
                                </div>
                              </div>
                              
                              <div style={{
                                background: 'rgba(59, 130, 246, 0.1)',
                                padding: '8px',
                                borderRadius: '8px',
                                border: '1px solid rgba(59, 130, 246, 0.2)'
                              }}>
                                <div style={{color: '#6b7280', fontSize: '11px', marginBottom: '2px'}}>Category</div>
                                <div style={{color: '#3b82f6', fontWeight: '600'}}>{normalizeCategoryDisplay(program.category) || '—'}</div>
                              </div>
                              
                              <div style={{
                                background: 'rgba(139, 92, 246, 0.1)',
                                padding: '8px',
                                borderRadius: '8px',
                                border: '1px solid rgba(139, 92, 246, 0.2)'
                              }}>
                                <div style={{color: '#6b7280', fontSize: '11px', marginBottom: '2px'}}>Round</div>
                                <div style={{color: '#8b5cf6', fontWeight: '600'}}>{program.round || '—'}</div>
                              </div>
                            </div>
                            
                            {/* Competition Level Badge */}
                            <div style={{marginTop: '12px', textAlign: 'center'}}>
                              {(() => {
                                // Calculate competition based on difference between user rank and closing rank
                                const userRank = parseInt(String(rank || '').trim(), 10);
                                const closingRank = program.closing_rank ? parseInt(String(program.closing_rank).replace(/[,\s]/g, ''), 10) : 0;
                                
                                let competitionLevel = '—';
                                let bgColor = 'rgba(107, 114, 128, 0.1)';
                                let textColor = '#6b7280';
                                
                                if (!isNaN(userRank) && userRank > 0 && !isNaN(closingRank) && closingRank > 0) {
                                  const rankDifference = closingRank - userRank;
                                  const percentageDifference = (rankDifference / userRank) * 100;
                                  
                                  if (percentageDifference <= 50) {
                                    competitionLevel = 'High';
                                    bgColor = 'rgba(217, 119, 6, 0.1)';
                                    textColor = '#d97706';
                                  } else {
                                    competitionLevel = 'Medium';
                                    bgColor = 'rgba(37, 99, 235, 0.1)';
                                    textColor = '#2563eb';
                                  }
                                } else if (!isNaN(closingRank) && closingRank > 0) {
                                  competitionLevel = 'Medium';
                                  bgColor = 'rgba(37, 99, 235, 0.1)';
                                  textColor = '#2563eb';
                                }
                                
                                return (
                                  <span style={{
                                    padding: '6px 12px',
                                    borderRadius: '15px',
                                    fontSize: '11px',
                                    fontWeight: '600',
                                    background: bgColor,
                                    color: textColor,
                                    border: '1px solid rgba(255,255,255,0.2)',
                                    backdropFilter: 'blur(5px)'
                                  }}>
                                    Competition: {competitionLevel}
                                  </span>
                                );
                              })()}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
            
            {/* Table View */}
            {cutoffViewMode === 'table' && (
              <div style={{
                background: 'rgba(255,255,255,0.05)',
                borderRadius: '15px',
                border: '1px solid rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)',
                overflow: 'hidden',
                boxShadow: '0 8px 32px rgba(0,0,0,0.1)'
              }}>
                <div style={{
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  padding: '15px 20px',
                  color: 'white'
                }}>
                  <h4 style={{margin: '0', fontSize: '18px', fontWeight: '600'}}>
                    📊 All Programs Comparison Table
                  </h4>
                </div>
                
                <div style={{overflowX: 'auto'}}>
                  <table style={{
                    width: '100%',
                    borderCollapse: 'collapse',
                    fontSize: '14px'
                  }}>
                    <thead>
                      <tr style={{
                        background: 'rgba(255,255,255,0.1)',
                        borderBottom: '2px solid rgba(255,255,255,0.2)'
                      }}>
                        <th style={{padding: '12px', textAlign: 'left', fontWeight: '600', color: '#2d3748'}}>College</th>
                        <th style={{padding: '12px', textAlign: 'left', fontWeight: '600', color: '#2d3748'}}>Program</th>
                        <th style={{padding: '12px', textAlign: 'center', fontWeight: '600', color: '#2d3748'}}>Open Rank</th>
                        <th style={{padding: '12px', textAlign: 'center', fontWeight: '600', color: '#2d3748'}}>Closing Rank</th>
                        <th style={{padding: '12px', textAlign: 'center', fontWeight: '600', color: '#2d3748'}}>Category</th>
                        <th style={{padding: '12px', textAlign: 'center', fontWeight: '600', color: '#2d3748'}}>Round</th>
                        <th style={{padding: '12px', textAlign: 'center', fontWeight: '600', color: '#2d3748'}}>Competition</th>
                      </tr>
                    </thead>
                    <tbody>
                      {processCollegeCutoffs.processedColleges.map((college, collegeIndex) => 
                        college.programs.map((program, programIndex) => (
                          <tr key={`${collegeIndex}-${programIndex}`} style={{
                            borderBottom: '1px solid rgba(255,255,255,0.1)',
                            transition: 'all 0.2s ease'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'transparent';
                          }}>
                            <td style={{padding: '12px', fontWeight: '500', color: '#4a5568'}}>
                              {college.college_name}
                            </td>
                            <td style={{padding: '12px', fontWeight: '500', color: '#2d3748'}}>
                              {program.course_name}
                            </td>
                            <td style={{padding: '12px', textAlign: 'center', color: '#10b981', fontWeight: '600'}}>
                              {formatRank(program.open_rank, program.open_rank_formatted)}
                            </td>
                            <td style={{padding: '12px', textAlign: 'center', color: '#f59e0b', fontWeight: '600'}}>
                              {formatRank(program.closing_rank, program.closing_rank_formatted)}
                            </td>
                            <td style={{padding: '12px', textAlign: 'center', color: '#3b82f6', fontWeight: '500'}}>
                              {normalizeCategoryDisplay(program.category) || '—'}
                            </td>
                            <td style={{padding: '12px', textAlign: 'center', color: '#8b5cf6', fontWeight: '500'}}>
                              {program.round || '—'}
                            </td>
                            <td style={{padding: '12px', textAlign: 'center'}}>
                              {(() => {
                                // Calculate competition based on difference between user rank and closing rank
                                const userRank = parseInt(String(rank || '').trim(), 10);
                                const closingRank = program.closing_rank ? parseInt(String(program.closing_rank).replace(/[,\s]/g, ''), 10) : 0;
                                
                                let competitionLevel = '—';
                                let bgColor = 'rgba(107, 114, 128, 0.1)';
                                let textColor = '#6b7280';
                                
                                if (!isNaN(userRank) && userRank > 0 && !isNaN(closingRank) && closingRank > 0) {
                                  const rankDifference = closingRank - userRank;
                                  const percentageDifference = (rankDifference / userRank) * 100;
                                  
                                  if (percentageDifference <= 50) {
                                    competitionLevel = 'High';
                                    bgColor = 'rgba(217, 119, 6, 0.1)';
                                    textColor = '#d97706';
                                  } else {
                                    competitionLevel = 'Medium';
                                    bgColor = 'rgba(37, 99, 235, 0.1)';
                                    textColor = '#2563eb';
                                  }
                                } else if (!isNaN(closingRank) && closingRank > 0) {
                                  competitionLevel = 'Medium';
                                  bgColor = 'rgba(37, 99, 235, 0.1)';
                                  textColor = '#2563eb';
                                }
                                
                                return (
                                  <span style={{
                                    padding: '4px 8px',
                                    borderRadius: '12px',
                                    fontSize: '11px',
                                    fontWeight: '600',
                                    background: bgColor,
                                    color: textColor
                                  }}>
                                    {competitionLevel}
                                  </span>
                                );
                              })()}
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
            
            {/* Compact View */}
            {cutoffViewMode === 'compact' && (
              <div style={{
                background: 'rgba(255,255,255,0.05)',
                borderRadius: '15px',
                border: '1px solid rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)',
                overflow: 'hidden',
                boxShadow: '0 8px 32px rgba(0,0,0,0.1)'
              }}>
                <div style={{
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  padding: '15px 20px',
                  color: 'white'
                }}>
                  <h4 style={{margin: '0', fontSize: '18px', fontWeight: '600'}}>
                    📋 Compact Program List
                  </h4>
                </div>
                
                <div style={{padding: '20px'}}>
                  <div style={{display: 'grid', gap: '8px'}}>
                    {processCollegeCutoffs.processedColleges.map((college, collegeIndex) => 
                      college.programs.map((program, programIndex) => (
                        <div key={`${collegeIndex}-${programIndex}`} style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          padding: '12px 16px',
                          background: 'rgba(255,255,255,0.05)',
                          borderRadius: '10px',
                          border: '1px solid rgba(255,255,255,0.1)',
                          transition: 'all 0.2s ease'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = 'rgba(255,255,255,0.1)';
                          e.currentTarget.style.transform = 'translateX(5px)';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                          e.currentTarget.style.transform = 'translateX(0)';
                        }}>
                          <div style={{flex: '1'}}>
                            <div style={{fontWeight: '600', color: '#2d3748', fontSize: '14px'}}>
                              {program.course_name}
                            </div>
                            <div style={{fontSize: '12px', color: '#6b7280', marginTop: '2px'}}>
                              {college.college_name}
                            </div>
                          </div>
                          
                          <div style={{display: 'flex', gap: '20px', alignItems: 'center'}}>
                            <div style={{textAlign: 'center'}}>
                              <div style={{fontSize: '11px', color: '#6b7280'}}>Open</div>
                              <div style={{fontSize: '13px', fontWeight: '600', color: '#10b981'}}>
                                {formatRank(program.open_rank, program.open_rank_formatted)}
                              </div>
                            </div>
                            <div style={{textAlign: 'center'}}>
                              <div style={{fontSize: '11px', color: '#6b7280'}}>Closing</div>
                              <div style={{fontSize: '13px', fontWeight: '600', color: '#f59e0b'}}>
                                {formatRank(program.closing_rank, program.closing_rank_formatted)}
                              </div>
                            </div>
                            <div style={{textAlign: 'center'}}>
                              <div style={{fontSize: '11px', color: '#6b7280'}}>Category</div>
                              <div style={{fontSize: '13px', fontWeight: '600', color: '#3b82f6'}}>
                                {normalizeCategoryDisplay(program.category) || '—'}
                              </div>
                            </div>
                            <div style={{textAlign: 'center'}}>
                              <div style={{fontSize: '11px', color: '#6b7280'}}>Round</div>
                              <div style={{fontSize: '13px', fontWeight: '600', color: '#8b5cf6'}}>
                                {program.round || '—'}
                              </div>
                            </div>
                            <div style={{textAlign: 'center'}}>
                              {(() => {
                                // Calculate competition based on difference between user rank and closing rank
                                const userRank = parseInt(String(rank || '').trim(), 10);
                                const closingRank = program.closing_rank ? parseInt(String(program.closing_rank).replace(/[,\s]/g, ''), 10) : 0;
                                
                                let competitionLevel = '—';
                                let bgColor = 'rgba(107, 114, 128, 0.1)';
                                let textColor = '#6b7280';
                                
                                if (!isNaN(userRank) && userRank > 0 && !isNaN(closingRank) && closingRank > 0) {
                                  const rankDifference = closingRank - userRank;
                                  const percentageDifference = (rankDifference / userRank) * 100;
                                  
                                  if (percentageDifference <= 50) {
                                    competitionLevel = 'High';
                                    bgColor = 'rgba(217, 119, 6, 0.1)';
                                    textColor = '#d97706';
                                  } else {
                                    competitionLevel = 'Medium';
                                    bgColor = 'rgba(37, 99, 235, 0.1)';
                                    textColor = '#2563eb';
                                  }
                                } else if (!isNaN(closingRank) && closingRank > 0) {
                                  competitionLevel = 'Medium';
                                  bgColor = 'rgba(37, 99, 235, 0.1)';
                                  textColor = '#2563eb';
                                }
                                
                                return (
                                  <span style={{
                                    padding: '4px 8px',
                                    borderRadius: '12px',
                                    fontSize: '11px',
                                    fontWeight: '600',
                                    background: bgColor,
                                    color: textColor
                                  }}>
                                    {competitionLevel}
                                  </span>
                                );
                              })()}
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
        
        {/* 🎓 Course-based College Search Section */}
        <div style={{
          marginTop: '50px',
          padding: '0',
          background: 'white',
          borderRadius: '16px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
          border: '1px solid #e5e7eb',
          overflow: 'hidden'
        }}>
          {/* Header Section */}
          <div style={{
            background: 'linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)',
            padding: '30px',
            color: 'white'
          }}>
            <h3 style={{
              fontSize: '26px',
              fontWeight: '700',
              margin: '0 0 8px 0',
              display: 'flex',
              alignItems: 'center',
              gap: '12px'
            }}>
              <span style={{fontSize: '30px'}}>🎓</span>
              Find Colleges by Course
            </h3>
            <p style={{
              color: 'rgba(255,255,255,0.9)',
              fontSize: '15px',
              margin: 0
            }}>
              Select a course to view all colleges offering that program with complete details
            </p>
          </div>
          
          {/* Course and City Selection */}
          <div style={{
            padding: '25px',
            background: '#f9fafb',
            borderBottom: '1px solid #e5e7eb'
          }}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
              gap: '20px',
              marginBottom: '0'
            }}>
              <div>
                <label style={{
                  display: 'block',
                  color: '#374151',
                  fontWeight: '600',
                  marginBottom: '12px',
                  fontSize: '15px'
                }}>
                  Select Course:
                </label>
                <select
                  value={selectedCourseForColleges}
                  onChange={async (e) => {
                    const course = e.target.value;
                    setSelectedCourseForColleges(course);
                    setCollegePage(1); // Reset to first page when course changes
                    await fetchCollegesByCourse(course, selectedCityForColleges);
                  }}
                  style={{
                    width: '100%',
                    maxWidth: '600px',
                    padding: '12px 16px',
                    borderRadius: '10px',
                    border: '2px solid #d1d5db',
                    background: 'white',
                    fontSize: '15px',
                    fontWeight: '500',
                    color: '#1f2937',
                    cursor: 'pointer',
                    outline: 'none',
                    transition: 'all 0.2s ease'
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = '#3b82f6';
                    e.target.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.1)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = '#d1d5db';
                    e.target.style.boxShadow = 'none';
                  }}
                >
                  <option value="">-- Select a Course --</option>
                  {programs.map((prog, idx) => (
                    <option key={idx} value={prog}>{prog}</option>
                  ))}
                </select>
              </div>
              
              <div>
                <label style={{
                  display: 'block',
                  color: '#374151',
                  fontWeight: '600',
                  marginBottom: '12px',
                  fontSize: '15px'
                }}>
                  Select City (Optional):
                </label>
                <select
                  value={selectedCityForColleges}
                  onChange={async (e) => {
                    const city = e.target.value;
                    setSelectedCityForColleges(city);
                    setCollegePage(1); // Reset to first page when city changes
                    if (selectedCourseForColleges) {
                      await fetchCollegesByCourse(selectedCourseForColleges, city);
                    }
                  }}
                  style={{
                    width: '100%',
                    maxWidth: '600px',
                    padding: '12px 16px',
                    borderRadius: '10px',
                    border: '2px solid #d1d5db',
                    background: 'white',
                    fontSize: '15px',
                    fontWeight: '500',
                    color: '#1f2937',
                    cursor: 'pointer',
                    outline: 'none',
                    transition: 'all 0.2s ease'
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = '#3b82f6';
                    e.target.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.1)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = '#d1d5db';
                    e.target.style.boxShadow = 'none';
                  }}
                >
                  <option value="">-- All Cities --</option>
                  {cities && cities.length > 0 ? (
                    cities.map((city, idx) => (
                      <option key={idx} value={city}>{city}</option>
                    ))
                  ) : (
                    <option disabled>Loading cities...</option>
                  )}
                </select>
              </div>
            </div>
          </div>
          
          {/* Loading State */}
          {isLoadingCollegesByCourse && (
            <div style={{
              textAlign: 'center',
              padding: '60px 20px',
              background: '#f9fafb'
            }}>
              <div style={{
                display: 'inline-block',
                width: '40px',
                height: '40px',
                border: '3px solid #e5e7eb',
                borderTop: '3px solid #3b82f6',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite'
              }}></div>
              <p style={{marginTop: '15px', fontSize: '15px', color: '#6b7280'}}>Loading colleges...</p>
            </div>
          )}
          
          {/* Colleges Display - Comprehensive Table Layout */}
          {!isLoadingCollegesByCourse && selectedCourseForColleges && collegesByCourse.length > 0 && (
            <div style={{padding: '25px', background: '#f9fafb'}}>
              <div style={{
                marginBottom: '20px',
                padding: '15px',
                background: 'white',
                borderRadius: '10px',
                border: '1px solid #e5e7eb',
                display: 'flex',
                alignItems: 'center',
                gap: '10px'
              }}>
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '50%',
                  background: 'linear-gradient(135deg, #3b82f6 0%, #1e40af 100%)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: 'white',
                  fontWeight: '700',
                  fontSize: '16px'
                }}>
                  {collegesByCourse.length}
                </div>
                <div>
                  <div style={{fontSize: '16px', fontWeight: '600', color: '#1f2937'}}>
                    Colleges offering <strong style={{color: '#3b82f6'}}>{selectedCourseForColleges}</strong>
                  </div>
                  <div style={{fontSize: '13px', color: '#6b7280', marginTop: '2px'}}>
                    Complete information displayed in table format
                  </div>
                </div>
              </div>
              
              {/* Main Colleges Table */}
              <div className="rank-finder-table-container" style={{
                background: 'white',
                borderRadius: '12px',
                border: '1px solid #e5e7eb',
                overflow: 'hidden',
                boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                marginTop: '0'
              }}>
                <div style={{
                  width: '100%',
                  overflowX: 'auto',
                  overflowY: 'visible'
                }}>
                  <table className="rank-finder-table" style={{
                    width: '100%',
                    borderCollapse: 'collapse',
                    fontSize: '13px',
                    minWidth: '1400px' // Allow horizontal scroll on mobile like rank finder
                  }}>
                    <thead>
                      <tr>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Institute Name</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Address</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>District</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>University</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Contact</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Website</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Hostel</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Branch</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'left'}}>Facilities</th>
                        <th style={{padding:'15px 12px', fontSize:'14px', fontWeight:'600', textAlign:'right'}}>Fee (₹)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(() => {
                        // Pagination logic
                        const startIndex = (collegePage - 1) * collegePageSize;
                        const endIndex = startIndex + collegePageSize;
                        const paginatedColleges = collegesByCourse.slice(startIndex, endIndex);
                        const totalPages = Math.ceil(collegesByCourse.length / collegePageSize);
                        
                        return paginatedColleges.map((college, idx) => {
                        try {
                          // Validate college object
                          if (!college || typeof college !== 'object') {
                            throw new Error('Invalid college object');
                          }
                          
                          // Parse college name and address to extract all information
                          const fullName = college.name || '';
                          const fullAddress = college.address || '';
                          const combinedText = (fullName + ' ' + fullAddress).trim();
                          
                          // Extract contact number from name or address
                          const contactMatch = combinedText.match(/Contact\s+No[:\s]*([\d\s\-]+)/i);
                          const extractedContact = contactMatch ? contactMatch[1].trim() : null;
                          
                          // Extract email from name or address
                          const emailMatch = combinedText.match(/Email[:\s]*([^\s,]+@[^\s,]+)/i);
                          const extractedEmail = emailMatch ? emailMatch[1].trim() : null;
                          
                          // Extract website from name or address - improved regex to capture valid URLs only
                          let extractedWebsite = null;
                          
                          // Try multiple patterns to find website
                          // Pattern 1: "Website: www.domain.com" or "Website: domain.com"
                          const websiteMatch1 = combinedText.match(/(?:Website|W)[:\s]+(?:www\.)?([a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
                          if (websiteMatch1 && websiteMatch1[1]) {
                            let website = websiteMatch1[1].trim();
                            // Validate it's a proper domain (has TLD)
                            if (/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(website)) {
                              if (!website.startsWith('www.') && !website.startsWith('http')) {
                                extractedWebsite = 'www.' + website;
                              } else {
                                extractedWebsite = website;
                              }
                            }
                          }
                          
                          // Pattern 2: "www.domain.com" or "http://domain.com" or "https://domain.com"
                          if (!extractedWebsite) {
                            const websiteMatch2 = combinedText.match(/(?:https?:\/\/|www\.)([a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
                            if (websiteMatch2 && websiteMatch2[1]) {
                              let website = websiteMatch2[1].trim();
                              if (/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(website)) {
                                if (combinedText.match(/https?:\/\//i)) {
                                  extractedWebsite = combinedText.match(/(https?:\/\/[^\s,]+)/i)?.[1] || null;
                                } else {
                                  extractedWebsite = 'www.' + website;
                                }
                              }
                            }
                          }
                          
                          // Clean extracted website - remove any trailing punctuation or invalid characters
                          if (extractedWebsite) {
                            extractedWebsite = extractedWebsite
                              .replace(/[.,;:!?]+$/, '') // Remove trailing punctuation
                              .replace(/\s+/g, '') // Remove spaces
                              .trim();
                            
                            // Final validation - must be a valid domain format
                            if (!/^(https?:\/\/)?(www\.)?[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(extractedWebsite)) {
                              extractedWebsite = null;
                            }
                          }
                          
                          // Extract district from address or name
                          let extractedDistrict = null;
                          // Try to extract district from address field first
                          if (fullAddress) {
                            // Look for district patterns in address (e.g., "Ahmedabad District", "Kheda Dist")
                            const districtMatch = fullAddress.match(/\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s*(?:District|Dist\.?)/i);
                            if (districtMatch) {
                              extractedDistrict = districtMatch[1].trim();
                            }
                          }
                          // If not found, try from name
                          if (!extractedDistrict && fullName) {
                            const districtMatch = fullName.match(/\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s*(?:District|Dist\.?)/i);
                            if (districtMatch) {
                              extractedDistrict = districtMatch[1].trim();
                            }
                          }
                          // Also check if district is in the database field
                          if (!extractedDistrict && college.district) {
                            extractedDistrict = college.district;
                          }
                          
                          // Extract address parts (At, Post, Near patterns) - but exclude district, email, website, contact
                          let extractedAddress = '';
                          
                          // Improved regex that stops at Contact/Email/Website patterns
                          const atMatch = combinedText.match(/At\s+([^,]+?)(?:\s*,\s*|Contact|Email|Website|$)/i);
                          const postMatch = combinedText.match(/Post\s+([^,]+?)(?:\s*,\s*|Contact|Email|Website|$)/i);
                          const nearMatch = combinedText.match(/Near\s+([^,]+?)(?:\s*,\s*|Contact|Email|Website|$)/i);
                          
                          // Helper function to clean address parts - removes contact/email/website
                          const cleanAddressPart = (part) => {
                            if (!part) return '';
                            return part
                              .replace(/\s*Contact\s+No[:\s]*[\d\s\-()]+/gi, '')
                              .replace(/\s*Phone[:\s]*[\d\s\-()]+/gi, '')
                              .replace(/\s*Tel[:\s]*[\d\s\-()]+/gi, '')
                              .replace(/\s*Mob[:\s]*[\d\s\-()]+/gi, '')
                              .replace(/\s*Email[:\s]*[^\s,]+@[^\s,]+\s*/gi, '')
                              .replace(/\s*[^\s,]+@[^\s,]+\s*/gi, '')
                              .replace(/\s*Website[:\s]*[^\s,]+/gi, '')
                              .replace(/\s*W\s+www\.[^\s,]+\s*/gi, '')
                              .replace(/\s*www\.[^\s,]+\s*/gi, '')
                              .replace(/\s*https?:\/\/[^\s,]+\s*/gi, '')
                              .replace(/\s+/g, ' ')
                              .trim();
                          };
                          
                          if (atMatch && atMatch[1]) {
                            const cleaned = cleanAddressPart(atMatch[1].trim());
                            if (cleaned && !cleaned.match(/Contact|Email|Website|@|www\.|http/i)) {
                              extractedAddress += (extractedAddress ? ', ' : '') + 'At ' + cleaned;
                            }
                          }
                          if (postMatch && postMatch[1]) {
                            const cleaned = cleanAddressPart(postMatch[1].trim());
                            if (cleaned && !cleaned.match(/Contact|Email|Website|@|www\.|http/i)) {
                              extractedAddress += (extractedAddress ? ', ' : '') + 'Post ' + cleaned;
                            }
                          }
                          if (nearMatch && nearMatch[1]) {
                            const cleaned = cleanAddressPart(nearMatch[1].trim());
                            if (cleaned && !cleaned.match(/Contact|Email|Website|@|www\.|http/i)) {
                              extractedAddress += (extractedAddress ? ', ' : '') + 'Near ' + cleaned;
                            }
                          }
                          
                          // Clean college name - remove all extracted information
                          let cleanCollegeName = fullName
                            .replace(/\s*Contact\s+No[:\s]*[\d\s\-]+/gi, '')
                            .replace(/\s*Email[:\s]*[^\s]+@[^\s]+\s*/gi, '')
                            .replace(/\s*Website[:\s]*[^\s]+\s*/gi, '')
                            .replace(/\s*W\s+www\.[^\s]+\s*/gi, '')
                            .replace(/\s*At\s+[^,]+/gi, '')
                            .replace(/\s*Post\s+[^,]+/gi, '')
                            .replace(/\s*Near\s+[^,]+/gi, '')
                            .replace(/\s*,\s*,/g, ',') // Remove double commas
                            .replace(/\s*,\s*$/g, '') // Remove trailing comma
                            .replace(/^\s*,\s*/g, '') // Remove leading comma
                            .trim();
                          
                          // If name still contains commas, take only the first part (usually the actual name)
                          if (cleanCollegeName.includes(',')) {
                            const parts = cleanCollegeName.split(',').map(p => p.trim()).filter(p => p);
                            cleanCollegeName = parts[0];
                            // If we don't have address yet, use remaining parts (but exclude district, email, website)
                            if (!extractedAddress && parts.length > 1) {
                              const addressParts = parts.slice(1).filter(p => {
                                const pLower = p.toLowerCase();
                                return !pLower.includes('@') && 
                                       !pLower.includes('www.') && 
                                       !pLower.includes('website') &&
                                       !pLower.includes('district') &&
                                       !pLower.includes('dist');
                              });
                              if (addressParts.length > 0) {
                                extractedAddress = addressParts.join(', ');
                              }
                            }
                          }
                          
                          // Clean address - remove ALL non-address information (email, website, district, contact, city, state, pincode)
                          // This function will be used multiple times to ensure thorough cleaning
                          const cleanAddressString = (addr) => {
                            if (!addr) return '';
                            
                            let cleaned = addr;
                            
                            // Remove district if it was extracted
                            if (extractedDistrict) {
                              cleaned = cleaned
                                .replace(new RegExp(`\\b${extractedDistrict.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*(?:District|Dist\\.?)`, 'gi'), '')
                                .replace(/\s*District[:\s]*[^,]+/gi, '')
                                .replace(/\s*Dist[:\s]*[^,]+/gi, '');
                            }
                            
                            // Remove all non-address information - multiple passes for thoroughness
                            for (let i = 0; i < 3; i++) { // Multiple passes to catch nested patterns
                              cleaned = cleaned
                                // Remove contact information (various formats)
                                .replace(/\s*Contact\s+No[:\s]*[\d\s\-()]+/gi, '')
                                .replace(/\s*Contact[:\s]*[\d\s\-()]+/gi, '')
                                .replace(/\s*Phone[:\s]*[\d\s\-()]+/gi, '')
                                .replace(/\s*Tel[:\s]*[\d\s\-()]+/gi, '')
                                .replace(/\s*Mob[:\s]*[\d\s\-()]+/gi, '')
                                .replace(/\s*Mobile[:\s]*[\d\s\-()]+/gi, '')
                                // Remove email (various formats)
                                .replace(/\s*Email[:\s]*[^\s,]+@[^\s,]+\s*/gi, '')
                                .replace(/\s*E-mail[:\s]*[^\s,]+@[^\s,]+\s*/gi, '')
                                .replace(/\s*[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\s*/gi, '') // Standalone email pattern
                                // Remove website (various formats)
                                .replace(/\s*Website[:\s]*[^\s,]+/gi, '')
                                .replace(/\s*W\s+www\.[^\s,]+\s*/gi, '')
                                .replace(/\s*www\.[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\s*/gi, '') // www.domain.com pattern
                                .replace(/\s*https?:\/\/[^\s,]+\s*/gi, '')
                                .replace(/\s*http:\/\/[^\s,]+\s*/gi, '')
                                .replace(/\s*https:\/\/[^\s,]+\s*/gi, '')
                                // Remove district
                                .replace(/\s*District[:\s]*[^,]+/gi, '')
                                .replace(/\s*Dist[:\s]*[^,]+/gi, '')
                                // Remove city, state, pincode if they appear as separate items
                                .replace(/\s*City[:\s]*[^,]+/gi, '')
                                .replace(/\s*State[:\s]*[^,]+/gi, '')
                                .replace(/\s*Pincode[:\s]*[\d\s]+/gi, '')
                                .replace(/\s*Pin[:\s]*[\d\s]+/gi, '')
                                .replace(/\s*PIN[:\s]*[\d\s]+/gi, '');
                            }
                            
                            // Clean up multiple commas and spaces
                            cleaned = cleaned
                              .replace(/\s*,\s*,/g, ',')
                              .replace(/\s*,\s*,\s*/g, ',')
                              .replace(/\s*,\s*$/g, '')
                              .replace(/^\s*,\s*/g, '')
                              .replace(/\s+/g, ' ') // Multiple spaces to single space
                              .trim();
                            
                            return cleaned;
                          };
                          
                          let cleanAddress = cleanAddressString(fullAddress || '');
                          
                          // Use extracted values or fall back to database values
                          const displayContact = extractedContact || college.contact_no || null;
                          const displayEmail = extractedEmail || college.email || null;
                          
                          // Validate and clean database website before using
                          let dbWebsite = null;
                          if (college.website && college.website !== '#' && college.website.trim() !== '') {
                            const cleanedDbWebsite = college.website.trim();
                            // Validate it's a proper URL/domain
                            if (/^(https?:\/\/)?(www\.)?[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(cleanedDbWebsite.replace(/^https?:\/\//, '').replace(/^www\./, ''))) {
                              dbWebsite = cleanedDbWebsite;
                            }
                          }
                          
                          // Extract website from email if website is not available
                          let websiteFromEmail = null;
                          if (!extractedWebsite && !dbWebsite && extractedEmail) {
                            // Extract domain from email (part after @)
                            const emailDomainMatch = extractedEmail.match(/@([a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
                            if (emailDomainMatch && emailDomainMatch[1]) {
                              const domain = emailDomainMatch[1].trim();
                              // Validate it's a proper domain
                              if (/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(domain)) {
                                websiteFromEmail = domain;
                              }
                            }
                          }
                          
                          // Also try to extract from database email if available
                          if (!extractedWebsite && !dbWebsite && !websiteFromEmail && college.email) {
                            const emailDomainMatch = college.email.match(/@([a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
                            if (emailDomainMatch && emailDomainMatch[1]) {
                              const domain = emailDomainMatch[1].trim();
                              if (/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(domain)) {
                                websiteFromEmail = domain;
                              }
                            }
                          }
                          
                          // Prefer extracted website, fallback to database website, then website from email
                          const displayWebsite = extractedWebsite || dbWebsite || websiteFromEmail;
                          
                          // Combine extracted address parts (At, Post, Near) with cleaned address
                          // Clean extracted address parts first using the same cleaning function
                          const cleanedExtractedAddress = extractedAddress ? cleanAddressString(extractedAddress) : '';
                          
                          // Combine cleaned parts
                          let finalAddress = '';
                          if (cleanedExtractedAddress) {
                            finalAddress = cleanedExtractedAddress;
                          }
                          if (cleanAddress) {
                            if (finalAddress) {
                              // Avoid duplicates - check if cleanAddress is already in finalAddress
                              if (!finalAddress.toLowerCase().includes(cleanAddress.toLowerCase()) && 
                                  !cleanAddress.toLowerCase().includes(finalAddress.toLowerCase())) {
                                finalAddress += ', ' + cleanAddress;
                              }
                            } else {
                              finalAddress = cleanAddress;
                            }
                          }
                          
                          // If we still don't have address, try using the raw address but clean it thoroughly
                          if (!finalAddress && fullAddress) {
                            finalAddress = cleanAddressString(fullAddress);
                          }
                          
                          // Final cleanup pass - remove any remaining contact/email/website that might have slipped through
                          if (finalAddress) {
                            // Apply cleaning function multiple times
                            finalAddress = cleanAddressString(finalAddress);
                            finalAddress = cleanAddressString(finalAddress); // Second pass
                            
                            // Split by comma and filter out any parts containing contact/email/website
                            const addressParts = finalAddress.split(',').map(p => p.trim()).filter(p => {
                              if (!p) return false;
                              const pLower = p.toLowerCase();
                              // Reject if contains email pattern
                              if (/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(p)) return false;
                              // Reject if contains website pattern
                              if (/www\.|https?:\/\//.test(p)) return false;
                              // Reject if contains contact keywords
                              if (/contact|phone|tel|mob|mobile|email|website|e-mail/i.test(p)) return false;
                              // Reject if it's just a number (likely a phone number)
                              if (/^\d{10,}$/.test(p.replace(/[\s\-()]/g, ''))) return false;
                              // Reject if it looks like a domain name
                              if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(p) && !p.includes(' ')) return false;
                              return true;
                            });
                            
                            // Rejoin valid address parts
                            finalAddress = addressParts.join(', ').trim();
                            
                            // One final aggressive cleanup
                            if (finalAddress) {
                              finalAddress = finalAddress
                                .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gi, '')
                                .replace(/www\.[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gi, '')
                                .replace(/https?:\/\/[^\s,]+/gi, '')
                                .replace(/http:\/\/[^\s,]+/gi, '')
                                .replace(/https:\/\/[^\s,]+/gi, '')
                                .replace(/\bContact[^,]*/gi, '')
                                .replace(/\bPhone[^,]*/gi, '')
                                .replace(/\bTel[^,]*/gi, '')
                                .replace(/\bMob[^,]*/gi, '')
                                .replace(/\bMobile[^,]*/gi, '')
                                .replace(/\bEmail[^,]*/gi, '')
                                .replace(/\bE-mail[^,]*/gi, '')
                                .replace(/\bWebsite[^,]*/gi, '')
                                .replace(/\bW\s+www\.[^,]*/gi, '')
                                .replace(/\s*,\s*,/g, ',')
                                .replace(/\s*,\s*,\s*/g, ',')
                                .replace(/\s*,\s*$/g, '')
                                .replace(/^\s*,\s*/g, '')
                                .replace(/\s+/g, ' ')
                                .trim();
                            }
                            
                            // Final validation - if still contains unwanted patterns, return null
                            if (finalAddress) {
                              const stillHasEmail = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(finalAddress);
                              const stillHasWebsite = /www\.|https?:\/\//.test(finalAddress);
                              const stillHasContact = /\b(Contact|Phone|Tel|Mob|Mobile|Email|E-mail|Website)\b/i.test(finalAddress);
                              
                              if (stillHasEmail || stillHasWebsite || stillHasContact) {
                                // Last resort: try to extract only the address-like parts
                                const safeParts = finalAddress.split(',').map(p => p.trim()).filter(p => {
                                  return p && 
                                         !/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(p) &&
                                         !/www\.|https?:\/\//.test(p) &&
                                         !/\b(Contact|Phone|Tel|Mob|Mobile|Email|E-mail|Website)\b/i.test(p);
                                });
                                finalAddress = safeParts.length > 0 ? safeParts.join(', ') : null;
                              }
                            }
                          }
                          
                          const displayAddress = finalAddress || null;
                          const displayDistrict = extractedDistrict || college.district || null;
                          
                          // Check if we have live data for this college
                          const hasLiveHostel = liveData[college.id]?.hostel;
                          const hasLiveFees = liveData[college.id]?.fees;
                          const hasLiveContact = liveData[college.id]?.contact;
                          
                          // Parse facilities - use database data for parsing (live data will be displayed separately)
                          const facilityText = (college.courses && Array.isArray(college.courses) && college.courses.length > 0 && college.courses[0]?.course_facility) 
                            ? college.courses[0].course_facility 
                            : (college.facility || null);
                        
                        const parseFacilities = (text) => {
                          const facilities = [];
                          if (!text || typeof text !== 'string' || !text.trim()) {
                            return facilities;
                          }
                          const parts = text.split(/[,;]/).map(p => p.trim()).filter(p => p);
                          
                          for (const part of parts) {
                            if (part.includes(':')) {
                              const [name, value] = part.split(':').map(s => s.trim());
                              const isAvailable = value && (
                                value.toLowerCase().includes('yes') || 
                                value.toLowerCase().includes('1') ||
                                value.toLowerCase() === 'y'
                              );
                              facilities.push({ name, value, isAvailable, raw: part });
                            } else {
                              facilities.push({ name: part, value: null, isAvailable: null, raw: part });
                            }
                          }
                          
                          if (facilities.length === 0 || facilities.every(f => !f.name.includes(':'))) {
                            const lines = text.split(/[\n\r]+/).map(l => l.trim()).filter(l => l);
                            if (lines.length > 0) {
                              facilities.length = 0;
                              for (const line of lines) {
                                if (line.includes(':')) {
                                  const [name, value] = line.split(':').map(s => s.trim());
                                  const isAvailable = value && (
                                    value.toLowerCase().includes('yes') || 
                                    value.toLowerCase().includes('1') ||
                                    value.toLowerCase() === 'y'
                                  );
                                  facilities.push({ name, value, isAvailable, raw: line });
                                } else {
                                  facilities.push({ name: line, value: null, isAvailable: null, raw: line });
                                }
                              }
                            }
                          }
                          
                          return facilities;
                        };
                        
                        // Parse facilities from all courses, not just the first one
                        const allCourseFacilities = [];
                        if (college.courses && Array.isArray(college.courses) && college.courses.length > 0) {
                          college.courses.forEach(course => {
                            if (course && course.course_facility && typeof course.course_facility === 'string') {
                              try {
                                const courseFacs = parseFacilities(course.course_facility);
                                if (Array.isArray(courseFacs)) {
                                  allCourseFacilities.push(...courseFacs);
                                }
                              } catch (e) {
                                console.error('Error parsing course facility:', e);
                              }
                            }
                          });
                        }
                        // Also parse from main facility text
                        const mainFacilities = (facilityText && typeof facilityText === 'string') ? parseFacilities(facilityText) : [];
                        const allFacilities = [...allCourseFacilities, ...mainFacilities];
                        
                        // Remove duplicates based on raw text
                        const uniqueFacilities = [];
                        const seen = new Set();
                        allFacilities.forEach(fac => {
                          const key = fac.raw || fac.name;
                          if (!seen.has(key)) {
                            seen.add(key);
                            uniqueFacilities.push(fac);
                          }
                        });
                        
                        // Extract boys and girls hostel information separately
                        let boysHostel = null;
                        let girlsHostel = null;
                        const otherFacilities = [];
                        
                        uniqueFacilities.forEach(fac => {
                          if (!fac || typeof fac !== 'object' || !fac.name) {
                            return; // Skip invalid facility objects
                          }
                          try {
                            const nameLower = (fac.name || '').toLowerCase();
                            if (nameLower.includes('boys') && (nameLower.includes('hostel') || nameLower.includes('accommodation'))) {
                              boysHostel = fac;
                            } else if (nameLower.includes('girls') && (nameLower.includes('hostel') || nameLower.includes('accommodation'))) {
                              girlsHostel = fac;
                            } else if (nameLower.includes('hostel') || nameLower.includes('accommodation')) {
                              // Generic hostel info (if not specifically boys/girls)
                              if (boysHostel === null) {
                                boysHostel = fac;
                              } else if (girlsHostel === null) {
                                girlsHostel = fac;
                              }
                            } else {
                              // All other facilities (Mess, Transportation, etc.) go to Other Facilities
                              otherFacilities.push(fac);
                            }
                          } catch (e) {
                            console.error('Error processing facility:', fac, e);
                          }
                        });
                        
                        // Also check facility text directly for boys/girls hostel patterns
                        if (facilityText && typeof facilityText === 'string') {
                          try {
                            const facilityLower = facilityText.toLowerCase();
                            // Check for "BOYS HOSTEL" or "BOYS HOSTEL: YES/NO"
                            if (facilityLower.includes('boys') && facilityLower.includes('hostel')) {
                              const boysMatch = facilityText.match(/boys\s+hostel[:\s]*([^,\n;]+)/i);
                              if (boysMatch && boysMatch[1]) {
                                boysHostel = {
                                  name: 'BOYS HOSTEL',
                                  value: boysMatch[1].trim(),
                                  isAvailable: boysMatch[1].toLowerCase().includes('yes') || boysMatch[1].toLowerCase().includes('1'),
                                  raw: boysMatch[0]
                                };
                              }
                            }
                            // Check for "GIRLS HOSTEL" or "GIRLS HOSTEL: YES/NO"
                            if (facilityLower.includes('girls') && facilityLower.includes('hostel')) {
                              const girlsMatch = facilityText.match(/girls\s+hostel[:\s]*([^,\n;]+)/i);
                              if (girlsMatch && girlsMatch[1]) {
                                girlsHostel = {
                                  name: 'GIRLS HOSTEL',
                                  value: girlsMatch[1].trim(),
                                  isAvailable: girlsMatch[1].toLowerCase().includes('yes') || girlsMatch[1].toLowerCase().includes('1'),
                                  raw: girlsMatch[0]
                                };
                              }
                            }
                          } catch (e) {
                            console.error('Error parsing facility text for hostel info:', e);
                          }
                        }
                        
                        // Get fee information - prioritize live data, then fees_detail, then course_fee
                        const liveFee = liveData[college.id]?.fees;
                        
                        // Collect all fee information from courses
                        const courseFees = [];
                        const feesDetails = [];
                        
                        if (college.courses && college.courses.length > 0) {
                          college.courses.forEach(course => {
                            if (course.course_fee) {
                              courseFees.push(course.course_fee);
                            }
                            if (course.course_fees_detail) {
                              feesDetails.push(course.course_fees_detail);
                            }
                          });
                        }
                        
                        // Calculate average fee
                        const avgFee = liveFee || (courseFees.length > 0 
                          ? Math.round(courseFees.reduce((a, b) => a + b, 0) / courseFees.length)
                          : (college.avg_fee_inr || null));
                        
                        // Parse fees_detail to extract boys and girls fees separately
                        let boysFees = null;
                        let girlsFees = null;
                        let otherFeesDetail = null;
                        
                        if (feesDetails && Array.isArray(feesDetails) && feesDetails.length > 0) {
                          try {
                            const combinedFeesDetail = feesDetails.filter(f => f && typeof f === 'string').join('; ');
                            if (combinedFeesDetail) {
                              // Extract BOYS FEES
                              const boysFeesMatch = combinedFeesDetail.match(/boys\s+fees?[:\s]*([^,\n;]+)/i);
                              if (boysFeesMatch && boysFeesMatch[1]) {
                                boysFees = boysFeesMatch[1].trim();
                              }
                              
                              // Extract GIRLS FEES
                              const girlsFeesMatch = combinedFeesDetail.match(/girls\s+fees?[:\s]*([^,\n;]+)/i);
                              if (girlsFeesMatch && girlsFeesMatch[1]) {
                                girlsFees = girlsFeesMatch[1].trim();
                              }
                              
                              // If no specific boys/girls fees found, use the whole text as other fees
                              if (!boysFees && !girlsFees) {
                                otherFeesDetail = combinedFeesDetail;
                              }
                            }
                          } catch (e) {
                            console.error('Error parsing fees detail:', e);
                            // Fallback to showing all fees detail
                            if (feesDetails.length > 0) {
                              otherFeesDetail = feesDetails.filter(f => f && typeof f === 'string').join('; ');
                            }
                          }
                        }
                        
                        return (
                          <tr key={college.id} style={{
                            borderBottom: '1px solid #e5e7eb',
                            transition: 'background 0.2s ease',
                            background: idx % 2 === 0 ? 'white' : '#f9fafb'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.background = '#eff6ff';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.background = idx % 2 === 0 ? 'white' : '#f9fafb';
                          }}>
                            {/* Institute Name */}
                            <td style={{
                              padding: '10px 8px',
                              fontWeight: '700',
                              color: '#1f2937',
                              background: idx % 2 === 0 ? 'white' : '#f8f9fa',
                              borderRight: '1px solid #dee2e6',
                              verticalAlign: 'top',
                              wordBreak: 'break-word'
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.background = '#e7f3ff';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.background = idx % 2 === 0 ? 'white' : '#f8f9fa';
                            }}>
                              <div style={{marginBottom: '4px', fontSize: '12px', lineHeight: '1.3', fontWeight: '600'}}>
                                {cleanCollegeName}
                                {(college.city || displayDistrict) && (
                                  <span style={{fontSize: '11px', color: '#6b7280', fontWeight: '400', marginLeft: '6px'}}>
                                    ({college.city || displayDistrict})
                                  </span>
                                )}
                              </div>
                              {college.inst_type && (
                                <span style={{
                                  display: 'inline-block',
                                  padding: '3px 8px',
                                  borderRadius: '3px',
                                  background: college.inst_type === 'GOVT' || college.inst_type === 'Government' 
                                    ? '#dbeafe' 
                                    : '#fef3c7',
                                  color: college.inst_type === 'GOVT' || college.inst_type === 'Government' 
                                    ? '#1e40af' 
                                    : '#92400e',
                                  fontWeight: '600',
                                  fontSize: '10px',
                                  textTransform: 'uppercase',
                                  letterSpacing: '0.3px'
                                }}>
                                  {college.inst_type}
                                </span>
                              )}
                              {college.code && (
                                <div style={{fontSize: '11px', color: '#6b7280', marginTop: '4px', fontFamily: 'monospace'}}>
                                  Code: {college.code}
                                </div>
                              )}
                            </td>
                            
                            {/* Address - ONLY Address (no district, email, website, contact, city, state, pincode) */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {displayAddress ? (
                                <div>
                                  <i className="fas fa-map-marker-alt" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                  <span>{displayAddress}</span>
                                </div>
                              ) : (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                              )}
                            </td>
                            
                            {/* District */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {displayDistrict ? (
                                <div style={{fontWeight: '500'}}>{displayDistrict}</div>
                              ) : (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                              )}
                            </td>
                            
                            {/* University / Affiliation */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {college.university && college.university.trim() !== '' && college.university !== 'null' ? (
                                <div>
                                  <i className="fas fa-university" style={{color: '#6b7280', marginRight: '6px', fontSize: '11px'}}></i>
                                  <span style={{fontWeight: '500'}}>{college.university.trim()}</span>
                                </div>
                              ) : (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                              )}
                            </td>
                            
                            {/* Contact Details */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {/* Show loading indicator while fetching */}
                              {fetchingLiveData[college.id] && !college.contact_no && !college.email && (
                                <div style={{
                                  padding: '6px 8px',
                                  background: '#eff6ff',
                                  border: '1px solid #bfdbfe',
                                  borderRadius: '4px',
                                  fontSize: '10px',
                                  color: '#3b82f6',
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '4px',
                                  marginBottom: '6px'
                                }}>
                                  <i className="fas fa-spinner fa-spin"></i>
                                  <span>Fetching...</span>
                                </div>
                              )}
                              
                              {/* Live Contact Data */}
                              {hasLiveContact ? (
                                <div style={{
                                  padding: '8px',
                                  background: '#f0fdf4',
                                  border: '1px solid #10b981',
                                  borderRadius: '4px',
                                  marginBottom: '6px',
                                  fontSize: '11px'
                                }}>
                                  <div style={{display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px'}}>
                                    <i className="fas fa-globe" style={{color: '#10b981', fontSize: '9px'}}></i>
                                    <span style={{color: '#059669', fontWeight: '600', fontSize: '10px'}}>LIVE</span>
                                  </div>
                                  {liveData[college.id].contact.phones && liveData[college.id].contact.phones.length > 0 && (
                                    <div style={{marginBottom: '3px'}}>
                                      <i className="fas fa-phone" style={{color: '#3b82f6', marginRight: '4px', fontSize: '10px'}}></i>
                                      <a href={`tel:${liveData[college.id].contact.phones[0]}`} style={{color: '#3b82f6', textDecoration: 'none', fontSize: '11px'}}>
                                        {liveData[college.id].contact.phones[0]}
                                      </a>
                                    </div>
                                  )}
                                  {liveData[college.id].contact.emails && liveData[college.id].contact.emails.length > 0 && (
                                    <div>
                                      <i className="fas fa-envelope" style={{color: '#3b82f6', marginRight: '4px', fontSize: '10px'}}></i>
                                      <a href={`mailto:${liveData[college.id].contact.emails[0]}`} style={{color: '#3b82f6', textDecoration: 'none', fontSize: '11px'}}>
                                        {liveData[college.id].contact.emails[0]}
                                      </a>
                                    </div>
                                  )}
                                </div>
                              ) : null}
                              
                              {displayContact ? (
                                <div style={{marginBottom: '4px', fontSize: '11px'}}>
                                  <i className="fas fa-phone" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                  <a href={`tel:${displayContact}`} style={{color: '#1e40af', textDecoration: 'none'}}>
                                    {displayContact}
                                  </a>
                                </div>
                              ) : college.contact_no ? (
                                <div style={{marginBottom: '4px', fontSize: '11px'}}>
                                  <i className="fas fa-phone" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                  <a href={`tel:${college.contact_no}`} style={{color: '#1e40af', textDecoration: 'none'}}>
                                    {college.contact_no}
                                  </a>
                                </div>
                              ) : null}
                              {displayEmail ? (
                                <div style={{marginBottom: '4px', fontSize: '11px'}}>
                                  <i className="fas fa-envelope" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                  <a href={`mailto:${displayEmail}`} style={{color: '#1e40af', textDecoration: 'none'}}>
                                    {displayEmail}
                                  </a>
                                </div>
                              ) : college.email ? (
                                <div style={{marginBottom: '4px', fontSize: '11px'}}>
                                  <i className="fas fa-envelope" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                  <a href={`mailto:${college.email}`} style={{color: '#1e40af', textDecoration: 'none'}}>
                                    {college.email}
                                  </a>
                                </div>
                              ) : null}
                              {!hasLiveContact && !displayContact && !college.contact_no && !displayEmail && !college.email && (
                                <div style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</div>
                              )}
                            </td>
                            
                            {/* Website */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {(() => {
                                // Format website for display
                                const formatWebsite = (url) => {
                                  if (!url) return null;
                                  
                                  // Remove protocol and www for display
                                  let display = url.replace(/^https?:\/\//, '').replace(/^www\./, '');
                                  
                                  // Ensure we have a valid domain
                                  if (!/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(display)) {
                                    return null;
                                  }
                                  
                                  // Format href - ensure it has protocol
                                  // For domains extracted from email (no www), use https:// directly
                                  let href = url;
                                  if (!href.startsWith('http://') && !href.startsWith('https://')) {
                                    // If it's just a domain (extracted from email), use https:// directly
                                    if (!href.startsWith('www.')) {
                                      href = 'https://' + href;
                                    } else {
                                      href = 'https://' + href;
                                    }
                                  }
                                  
                                  return { display, href };
                                };
                                
                                const websiteInfo = displayWebsite ? formatWebsite(displayWebsite) : null;
                                
                                return websiteInfo ? (
                                  <div>
                                    <i className="fas fa-globe" style={{color: '#6b7280', marginRight: '4px', fontSize: '10px'}}></i>
                                    <a href={websiteInfo.href} target="_blank" rel="noopener noreferrer" style={{color: '#1e40af', textDecoration: 'none', fontSize: '10px'}}>
                                      {websiteInfo.display}
                                    </a>
                                  </div>
                                ) : (
                                  <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                                );
                              })()}
                            </td>
                            
                            {/* Hostel Facility - Only Boys/Girls Hostel Info */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {/* Show loading indicator while fetching */}
                              {fetchingLiveData[college.id] && !boysHostel && !girlsHostel && (
                                <div style={{
                                  padding: '6px 8px',
                                  background: '#eff6ff',
                                  border: '1px solid #bfdbfe',
                                  borderRadius: '4px',
                                  fontSize: '10px',
                                  color: '#3b82f6',
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '4px',
                                  marginBottom: '6px'
                                }}>
                                  <i className="fas fa-spinner fa-spin"></i>
                                  <span>Fetching...</span>
                                </div>
                              )}
                              
                              {/* Display Live Data or Database Data */}
                              {hasLiveHostel ? (
                                <div style={{
                                  padding: '8px',
                                  background: '#f0fdf4',
                                  border: '1px solid #10b981',
                                  borderRadius: '4px',
                                  fontSize: '12px',
                                  marginBottom: (boysHostel || girlsHostel) ? '6px' : '0'
                                }}>
                                  <div style={{display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px'}}>
                                    <i className="fas fa-globe" style={{color: '#10b981', fontSize: '9px'}}></i>
                                    <span style={{color: '#059669', fontWeight: '600', fontSize: '10px'}}>LIVE</span>
                                  </div>
                                  <div style={{color: '#1f2937', lineHeight: '1.5', whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: '11px'}}>{liveData[college.id].hostel}</div>
                                </div>
                              ) : null}
                              
                              {/* Display Boys and Girls Hostel separately */}
                              {(boysHostel || girlsHostel) ? (
                                <div style={{display: 'flex', flexDirection: 'column', gap: '4px'}}>
                                  {boysHostel ? (
                                    <div style={{
                                      padding: '5px 8px',
                                      borderRadius: '3px',
                                      background: (boysHostel.isAvailable !== false) ? '#f0fdf4' : '#f9fafb',
                                      border: `1px solid ${(boysHostel.isAvailable !== false) ? '#10b981' : '#e5e7eb'}`,
                                      fontSize: '10px',
                                      fontWeight: '500',
                                      marginBottom: girlsHostel ? '3px' : '0'
                                    }}>
                                      <span style={{color: '#1f2937'}}>BOYS HOSTEL:</span>
                                      <span style={{color: (boysHostel.isAvailable !== false) ? '#059669' : '#9ca3af', marginLeft: '4px', fontWeight: '600'}}>
                                        {(boysHostel.value && boysHostel.value.trim()) || ((boysHostel.isAvailable !== false) ? 'YES' : 'NO')}
                                      </span>
                                    </div>
                                  ) : null}
                                  {girlsHostel ? (
                                    <div style={{
                                      padding: '5px 8px',
                                      borderRadius: '3px',
                                      background: (girlsHostel.isAvailable !== false) ? '#f0fdf4' : '#f9fafb',
                                      border: `1px solid ${(girlsHostel.isAvailable !== false) ? '#10b981' : '#e5e7eb'}`,
                                      fontSize: '10px',
                                      fontWeight: '500'
                                    }}>
                                      <span style={{color: '#1f2937'}}>GIRLS HOSTEL:</span>
                                      <span style={{color: (girlsHostel.isAvailable !== false) ? '#059669' : '#9ca3af', marginLeft: '4px', fontWeight: '600'}}>
                                        {(girlsHostel.value && girlsHostel.value.trim()) || ((girlsHostel.isAvailable !== false) ? 'YES' : 'NO')}
                                      </span>
                                    </div>
                                  ) : null}
                                </div>
                              ) : !hasLiveHostel && !boysHostel && !girlsHostel && !fetchingLiveData[college.id] ? (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                              ) : null}
                            </td>
                            
                            {/* Branch / Department - Show Program/Course Names */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {college.courses && Array.isArray(college.courses) && college.courses.length > 0 ? (
                                <div style={{display: 'flex', flexDirection: 'column', gap: '4px'}}>
                                  {college.courses.map((course, cIdx) => (
                                    <div key={cIdx} style={{
                                      padding: '6px 8px',
                                      borderRadius: '4px',
                                      background: '#eff6ff',
                                      border: '1px solid #bfdbfe',
                                      fontSize: '11px',
                                      fontWeight: '500',
                                      color: '#1e40af'
                                    }}>
                                      {course.course_name || course.name || 'N/A'}
                                    </div>
                                  ))}
                                </div>
                              ) : (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                              )}
                            </td>
                            
                            {/* Other Facilities - Show Only Transportation and Mess */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              background: 'transparent'
                            }}>
                              {(() => {
                                // Filter facilities to show only Transportation and Mess
                                const transportAndMess = otherFacilities.filter(fac => {
                                  if (!fac || !fac.name) return false;
                                  const nameLower = fac.name.toLowerCase();
                                  return nameLower.includes('transport') || nameLower.includes('mess');
                                });
                                
                                return transportAndMess.length > 0 ? (
                                  <div style={{display: 'flex', flexDirection: 'column', gap: '3px'}}>
                                    {transportAndMess.map((fac, fIdx) => (
                                      <div key={fIdx} style={{
                                        padding: '5px 8px',
                                        borderRadius: '3px',
                                        background: fac.isAvailable !== false ? '#f0fdf4' : '#f9fafb',
                                        border: `1px solid ${fac.isAvailable !== false ? '#bbf7d0' : '#e5e7eb'}`,
                                        fontSize: '10px',
                                        lineHeight: '1.4'
                                      }}>
                                        <span style={{fontWeight: '500', color: '#1f2937'}}>{fac.name}</span>
                                        {fac.value && (
                                          <span style={{color: fac.isAvailable !== false ? '#059669' : '#9ca3af', marginLeft: '4px'}}>
                                            : {fac.value}
                                          </span>
                                        )}
                                      </div>
                                    ))}
                                  </div>
                                ) : (
                                  <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '10px'}}>Information not available</span>
                                );
                              })()}
                            </td>
                            
                            {/* Annual Fee */}
                            <td style={{
                              padding: '12px',
                              fontSize: '13px',
                              color: '#1f2937',
                              fontWeight: '500',
                              background: 'transparent'
                            }}>
                              {/* Live Fee Data */}
                              {hasLiveFees ? (
                                <div style={{
                                  padding: '8px',
                                  background: '#f0fdf4',
                                  border: '1px solid #10b981',
                                  borderRadius: '4px',
                                  marginBottom: '6px'
                                }}>
                                  <div style={{display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px'}}>
                                    <i className="fas fa-globe" style={{color: '#10b981', fontSize: '9px'}}></i>
                                    <span style={{color: '#059669', fontWeight: '600', fontSize: '9px'}}>LIVE</span>
                                  </div>
                                  <div style={{fontSize: '14px', fontWeight: '700', color: '#059669'}}>
                                    ₹{liveData[college.id].fees.toLocaleString()}
                                  </div>
                                </div>
                              ) : null}
                              
                              {/* Display Boys and Girls Fees separately */}
                              {(boysFees || girlsFees || otherFeesDetail) ? (
                                <div style={{
                                  padding: '8px',
                                  background: '#f9fafb',
                                  border: '1px solid #e5e7eb',
                                  borderRadius: '4px',
                                  marginBottom: avgFee ? '6px' : '0',
                                  fontSize: '11px',
                                  lineHeight: '1.6',
                                  color: '#374151'
                                }}>
                                  {boysFees ? (
                                    <div style={{marginBottom: '4px'}}>
                                      <span style={{fontWeight: '600', color: '#1f2937'}}>BOYS FEES:</span>
                                      <span style={{color: '#059669', marginLeft: '4px', fontWeight: '500'}}>{boysFees}</span>
                                    </div>
                                  ) : null}
                                  {girlsFees ? (
                                    <div style={{marginBottom: boysFees ? '4px' : '0'}}>
                                      <span style={{fontWeight: '600', color: '#1f2937'}}>GIRLS FEES:</span>
                                      <span style={{color: '#059669', marginLeft: '4px', fontWeight: '500'}}>{girlsFees}</span>
                                    </div>
                                  ) : null}
                                  {otherFeesDetail && !boysFees && !girlsFees ? (
                                    <div>
                                      <div style={{fontWeight: '600', marginBottom: '4px', color: '#1f2937', fontSize: '12px'}}>Fee Details:</div>
                                      <div style={{whiteSpace: 'pre-wrap', wordBreak: 'break-word'}}>{otherFeesDetail}</div>
                                    </div>
                                  ) : null}
                                </div>
                              ) : null}
                              
                              {/* Average Fee */}
                              {avgFee && !hasLiveFees && !boysFees && !girlsFees && !otherFeesDetail ? (
                                <div>
                                  <div style={{fontSize: '14px', fontWeight: '700', color: '#059669'}}>₹{avgFee.toLocaleString()}</div>
                                  {college.courses && college.courses.length > 1 && courseFees.length > 0 && (
                                    <div style={{fontSize: '10px', color: '#6b7280', fontWeight: '400', marginTop: '2px'}}>
                                      (avg of {courseFees.length} courses)
                                    </div>
                                  )}
                                </div>
                              ) : !hasLiveFees && !avgFee && !boysFees && !girlsFees && !otherFeesDetail && !fetchingLiveData[college.id] ? (
                                <span style={{color: '#9ca3af', fontStyle: 'italic', fontWeight: '400', fontSize: '12px'}}>Information not available</span>
                              ) : null}
                            </td>
                            </tr>
                          );
                        } catch (error) {
                          console.error('Error processing college:', college?.name || 'Unknown', error);
                          console.error('Error details:', {
                            message: error.message,
                            stack: error.stack,
                            college: college ? {
                              id: college.id,
                              name: college.name,
                              hasCourses: !!college.courses,
                              coursesLength: college.courses?.length
                            } : 'college is null/undefined'
                          });
                          return (
                            <tr key={college?.id || idx} style={{
                              borderBottom: '1px solid #e5e7eb',
                              background: idx % 2 === 0 ? 'white' : '#f9fafb'
                            }}>
                              <td colSpan="10" style={{padding: '16px', color: '#dc2626', textAlign: 'center'}}>
                                Error loading college data: {college?.name || 'Unknown'}
                                <br />
                                <small style={{color: '#9ca3af', fontSize: '11px'}}>
                                  {error.message || 'Unknown error'}
                                </small>
                              </td>
                            </tr>
                          );
                        }
                      });
                      })()}
                    </tbody>
                  </table>
                </div>
                
                {/* Pagination Controls */}
                {collegesByCourse.length > collegePageSize && (
                  <div style={{
                    padding: '20px',
                    borderTop: '1px solid #e5e7eb',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    flexWrap: 'wrap',
                    gap: '10px'
                  }}>
                    <div style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                      fontSize: '13px',
                      color: '#6b7280'
                    }}>
                      <span>Showing</span>
                      <select
                        value={collegePageSize}
                        onChange={(e) => {
                          setCollegePageSize(Number(e.target.value));
                          setCollegePage(1);
                        }}
                        style={{
                          padding: '6px 10px',
                          borderRadius: '6px',
                          border: '1px solid #d1d5db',
                          fontSize: '13px'
                        }}
                      >
                        <option value={10}>10</option>
                        <option value={20}>20</option>
                        <option value={50}>50</option>
                        <option value={100}>100</option>
                      </select>
                      <span>of {collegesByCourse.length} colleges</span>
                    </div>
                    
                    <div style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px'
                    }}>
                      <button
                        onClick={() => setCollegePage(1)}
                        disabled={collegePage === 1}
                        style={{
                          padding: '8px 12px',
                          borderRadius: '6px',
                          border: '1px solid #d1d5db',
                          background: collegePage === 1 ? '#f3f4f6' : 'white',
                          color: collegePage === 1 ? '#9ca3af' : '#374151',
                          cursor: collegePage === 1 ? 'not-allowed' : 'pointer',
                          fontSize: '13px',
                          fontWeight: '500'
                        }}
                      >
                        First
                      </button>
                      <button
                        onClick={() => setCollegePage(prev => Math.max(1, prev - 1))}
                        disabled={collegePage === 1}
                        style={{
                          padding: '8px 12px',
                          borderRadius: '6px',
                          border: '1px solid #d1d5db',
                          background: collegePage === 1 ? '#f3f4f6' : 'white',
                          color: collegePage === 1 ? '#9ca3af' : '#374151',
                          cursor: collegePage === 1 ? 'not-allowed' : 'pointer',
                          fontSize: '13px',
                          fontWeight: '500'
                        }}
                      >
                        Previous
                      </button>
                      <span style={{
                        padding: '8px 12px',
                        fontSize: '13px',
                        color: '#374151',
                        fontWeight: '500'
                      }}>
                        Page {collegePage} of {Math.ceil(collegesByCourse.length / collegePageSize)}
                      </span>
                      <button
                        onClick={() => setCollegePage(prev => Math.min(Math.ceil(collegesByCourse.length / collegePageSize), prev + 1))}
                        disabled={collegePage >= Math.ceil(collegesByCourse.length / collegePageSize)}
                        style={{
                          padding: '8px 12px',
                          borderRadius: '6px',
                          border: '1px solid #d1d5db',
                          background: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? '#f3f4f6' : 'white',
                          color: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? '#9ca3af' : '#374151',
                          cursor: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? 'not-allowed' : 'pointer',
                          fontSize: '13px',
                          fontWeight: '500'
                        }}
                      >
                        Next
                      </button>
                      <button
                        onClick={() => setCollegePage(Math.ceil(collegesByCourse.length / collegePageSize))}
                        disabled={collegePage >= Math.ceil(collegesByCourse.length / collegePageSize)}
                        style={{
                          padding: '8px 12px',
                          borderRadius: '6px',
                          border: '1px solid #d1d5db',
                          background: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? '#f3f4f6' : 'white',
                          color: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? '#9ca3af' : '#374151',
                          cursor: collegePage >= Math.ceil(collegesByCourse.length / collegePageSize) ? 'not-allowed' : 'pointer',
                          fontSize: '13px',
                          fontWeight: '500'
                        }}
                      >
                        Last
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
          
          {/* No Results */}
          {!isLoadingCollegesByCourse && selectedCourseForColleges && collegesByCourse.length === 0 && (
            <div style={{
              textAlign: 'center',
              padding: '60px 20px',
              background: '#f9fafb'
            }}>
              <div style={{
                width: '80px',
                height: '80px',
                margin: '0 auto 20px',
                borderRadius: '50%',
                background: '#e5e7eb',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '36px'
              }}>🔍</div>
              <p style={{
                fontSize: '18px',
                fontWeight: '600',
                color: '#374151',
                margin: '0 0 8px 0'
              }}>
                No colleges found
              </p>
              <p style={{
                fontSize: '14px',
                color: '#6b7280',
                margin: 0
              }}>
                No colleges found offering <strong>{selectedCourseForColleges}</strong>
              </p>
            </div>
          )}
        </div>
    </div>

      {/* Notifications Section */}
      {notifications.length > 0 && (
        <div className="rank-finder-info-box" style={{
          marginTop: '2rem',
          marginBottom: '2rem',
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          borderRadius: '16px',
          padding: '24px',
          boxShadow: '0 8px 32px rgba(102, 126, 234, 0.3)',
          maxWidth: '1400px',
          marginLeft: 'auto',
          marginRight: 'auto'
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            marginBottom: '20px',
            color: 'white'
          }}>
            <i className="fas fa-bell" style={{fontSize: '24px'}}></i>
            <h3 style={{margin: 0, fontSize: '22px', fontWeight: '700', color: 'white'}}>
              Latest Notifications
            </h3>
          </div>
          
          {/* Latest Notification - Prominent Display */}
          {notifications.length > 0 && notifications[0] && (
            <div
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                try {
                  if (typeof openNotificationBrochure === 'function') {
                    openNotificationBrochure(notifications[0], 0);
                  } else {
                    const modal = document.getElementById('brochureModal');
                    const modalTitle = document.getElementById('brochureModalTitle');
                    if (modal && modalTitle) {
                      modalTitle.innerHTML = `<i className="fas fa-file-pdf me-2"></i>${notifications[0].title || 'Notification'}`;
                      if (typeof loadBrochureContent === 'function') {
                        loadBrochureContent(notifications[0], 0);
                      }
                      modal.style.display = 'flex';
                    } else if (notifications[0].url && notifications[0].url !== '#') {
                      window.open(notifications[0].url, '_blank');
                    }
                  }
                } catch (err) {
                  console.error('Error opening notification:', err);
                  if (notifications[0].url && notifications[0].url !== '#') {
                    window.open(notifications[0].url, '_blank');
                  }
                }
              }}
              style={{
                background: 'linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%)',
                borderRadius: '12px',
                padding: '20px',
                marginBottom: '20px',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                boxShadow: '0 6px 20px rgba(245, 158, 11, 0.4)',
                border: '2px solid rgba(255, 255, 255, 0.3)'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-2px)';
                e.currentTarget.style.boxShadow = '0 8px 28px rgba(245, 158, 11, 0.5)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)';
                e.currentTarget.style.boxShadow = '0 6px 20px rgba(245, 158, 11, 0.4)';
              }}
            >
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '10px',
                marginBottom: '12px',
                fontSize: '13px',
                color: '#78350f',
                fontWeight: '700'
              }}>
                <i className="fas fa-star" style={{color: '#fff'}}></i>
                <span style={{color: '#fff', textTransform: 'uppercase', letterSpacing: '0.5px'}}>Latest Notification</span>
                <i className="fas fa-calendar-alt" style={{color: '#fff', marginLeft: 'auto'}}></i>
                <span style={{color: '#fff'}}>{notifications[0].date || 'N/A'}</span>
              </div>
              <div style={{
                fontSize: '20px',
                fontWeight: '700',
                color: '#fff',
                marginBottom: '8px',
                lineHeight: '1.4'
              }}>
                {notifications[0].title || 'Notification'}
              </div>
              <div style={{
                fontSize: '13px',
                color: 'rgba(255, 255, 255, 0.9)',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                marginTop: '12px'
              }}>
                <i className="fas fa-file-pdf" style={{color: '#fff'}}></i>
                <span>Click to view full details</span>
              </div>
            </div>
          )}
          
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: '16px'
          }}>
            {notifications.slice(1, 7).map((n, i) => (
              <div
                key={i}
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  // Try to use the global openNotificationBrochure function
                  try {
                    if (typeof openNotificationBrochure === 'function') {
                      openNotificationBrochure(n, i);
                    } else {
                      // Fallback: manually open the modal
                      const modal = document.getElementById('brochureModal');
                      const modalTitle = document.getElementById('brochureModalTitle');
                      if (modal && modalTitle) {
                        modalTitle.innerHTML = `<i className="fas fa-file-pdf me-2"></i>${n.title || 'Notification'}`;
                        if (typeof loadBrochureContent === 'function') {
                          loadBrochureContent(n, i);
                        } else {
                          // Manual content loading
                          const modalContent = document.getElementById('brochureContent');
                          const downloadLink = document.getElementById('brochureDownloadLink');
                          if (modalContent) {
                            if (n.brochure_file) {
                              modalContent.innerHTML = `
                                <div className="brochure-pdf-container">
                                  <iframe 
                                    src="${n.brochure_file}" 
                                    width="100%" 
                                    height="500px"
                                    style="border: none; border-radius: 8px;"
                                    title="${n.title}">
                                  </iframe>
                                </div>
                              `;
                              if (downloadLink) {
                                downloadLink.href = n.brochure_file;
                                downloadLink.style.display = 'inline-block';
                              }
                            } else {
                              modalContent.innerHTML = `
                                <div className="brochure-info">
                                  <div className="brochure-header">
                                    <h4>${n.title || 'Notification'}</h4>
                                    <p className="brochure-date">
                                      <i className="fas fa-calendar-alt me-2"></i>${n.date || 'N/A'}
                                    </p>
                                  </div>
                                  <div className="brochure-description">
                                    <p>This notification contains important information regarding the admission process.</p>
                                    ${n.url && n.url !== '#' ? 
                                      `<p><strong>External Link:</strong> <a href="${n.url}" target="_blank" rel="noopener noreferrer">View Full Notification</a></p>` : 
                                      ''
                                    }
                                    ${n.brochure_title ? `<p><strong>Brochure:</strong> ${n.brochure_title}</p>` : ''}
                                  </div>
                                </div>
                              `;
                              if (downloadLink) {
                                downloadLink.style.display = 'none';
                              }
                            }
                          }
                        }
                        modal.style.display = 'flex';
                      } else if (n.url && n.url !== '#') {
                        window.open(n.url, '_blank');
                      }
                    }
                  } catch (err) {
                    console.error('Error opening notification:', err);
                    if (n.url && n.url !== '#') {
                      window.open(n.url, '_blank');
                    }
                  }
                }}
                style={{
                  background: 'white',
                  borderRadius: '12px',
                  padding: '16px',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease',
                  boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                  border: '1px solid rgba(255,255,255,0.2)'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-4px)';
                  e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.15)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
                }}
              >
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  marginBottom: '12px',
                  fontSize: '12px',
                  color: '#667eea',
                  fontWeight: '600'
                }}>
                  <i className="fas fa-calendar-alt"></i>
                  <span>{n.date || 'N/A'}</span>
                </div>
                <div style={{
                  fontSize: '16px',
                  fontWeight: '600',
                  color: '#1f2937',
                  marginBottom: '8px',
                  lineHeight: '1.4',
                  display: '-webkit-box',
                  WebkitLineClamp: 2,
                  WebkitBoxOrient: 'vertical',
                  overflow: 'hidden'
                }}>
                  {n.title || 'Notification'}
                </div>
                <div style={{
                  fontSize: '12px',
                  color: '#6b7280',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  marginTop: '8px'
                }}>
                  <i className="fas fa-file-pdf" style={{color: '#ef4444'}}></i>
                  <span>Click to view details</span>
                </div>
              </div>
            ))}
          </div>
          <div style={{
            textAlign: 'center',
            marginTop: '20px'
          }}>
            <button
              onClick={() => setShowAllNotifications(true)}
              style={{
                background: 'white',
                color: '#667eea',
                border: '2px solid white',
                padding: '12px 24px',
                borderRadius: '8px',
                fontSize: '14px',
                fontWeight: '600',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = '#f3f4f6';
                e.currentTarget.style.transform = 'translateY(-2px)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'white';
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              <i className="fas fa-list me-2"></i>
              View All Notifications ({notifications.length})
            </button>
          </div>
        </div>
      )}

      {/* Approved Boards Section */}
      <div className="rank-finder-info-box" style={{
        marginTop: '2rem',
        marginBottom: '2rem',
        background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
        borderRadius: '16px',
        padding: '24px',
        boxShadow: '0 8px 32px rgba(16, 185, 129, 0.3)',
        maxWidth: '1400px',
        marginLeft: 'auto',
        marginRight: 'auto'
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: '20px',
          color: 'white'
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px'
          }}>
            <i className="fas fa-graduation-cap" style={{fontSize: '24px'}}></i>
            <h3 style={{margin: 0, fontSize: '22px', fontWeight: '700', color: 'white'}}>
              Approved Education Boards
            </h3>
          </div>
          <button
            onClick={() => setShowApprovedBoards(!showApprovedBoards)}
            style={{
              background: 'rgba(255,255,255,0.2)',
              border: 'none',
              color: 'white',
              padding: '8px 16px',
              borderRadius: '8px',
              fontSize: '14px',
              fontWeight: '600',
              cursor: 'pointer',
              transition: 'all 0.3s ease'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.3)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.2)';
            }}
          >
            {showApprovedBoards ? 'Hide' : 'View'} Boards ({approvedBoards.length})
          </button>
        </div>
        
        {showApprovedBoards && (
          <div>
            {/* Filters */}
            <div style={{
              display: 'grid',
              gridTemplateColumns: '1fr 1fr',
              gap: '12px',
              marginBottom: '20px'
            }}>
              <div>
                <label style={{
                  display: 'block',
                  color: 'white',
                  fontSize: '14px',
                  fontWeight: '600',
                  marginBottom: '6px'
                }}>
                  Filter by State/UT
                </label>
                <select
                  value={boardFilter}
                  onChange={(e) => setBoardFilter(e.target.value)}
                  style={{
                    width: '100%',
                    padding: '10px',
                    borderRadius: '8px',
                    border: 'none',
                    fontSize: '14px',
                    background: 'white'
                  }}
                >
                  <option value="">All States/UTs</option>
                  {boardStates.map(state => (
                    <option key={state} value={state}>{state}</option>
                  ))}
                </select>
              </div>
              <div>
                <label style={{
                  display: 'block',
                  color: 'white',
                  fontSize: '14px',
                  fontWeight: '600',
                  marginBottom: '6px'
                }}>
                  Search Boards
                </label>
                <input
                  type="text"
                  value={boardSearch}
                  onChange={(e) => setBoardSearch(e.target.value)}
                  placeholder="Search by board name or state..."
                  style={{
                    width: '100%',
                    padding: '10px',
                    borderRadius: '8px',
                    border: 'none',
                    fontSize: '14px',
                    background: 'white'
                  }}
                />
              </div>
            </div>
            
            {/* Boards List */}
            {isLoadingBoards ? (
              <div style={{textAlign: 'center', padding: '40px', color: 'white'}}>
                <i className="fas fa-spinner fa-spin" style={{fontSize: '24px', marginRight: '10px'}}></i>
                Loading approved boards...
              </div>
            ) : filteredBoards.length === 0 ? (
              <div style={{textAlign: 'center', padding: '40px', color: 'white'}}>
                <i className="fas fa-info-circle" style={{fontSize: '24px', marginRight: '10px'}}></i>
                No boards found matching your criteria.
              </div>
            ) : (
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                gap: '16px',
                maxHeight: '600px',
                overflowY: 'auto',
                padding: '8px'
              }}>
                {filteredBoards.map((board) => (
                  <div
                    key={board.id}
                    style={{
                      background: 'white',
                      borderRadius: '12px',
                      padding: '16px',
                      transition: 'all 0.3s ease',
                      boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                      border: '1px solid rgba(255,255,255,0.2)'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.transform = 'translateY(-4px)';
                      e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.15)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.transform = 'translateY(0)';
                      e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
                    }}
                  >
                    <div style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                      marginBottom: '12px',
                      fontSize: '12px',
                      color: '#10b981',
                      fontWeight: '600'
                    }}>
                      <i className="fas fa-map-marker-alt"></i>
                      <span>{board.state_ut || 'N/A'}</span>
                    </div>
                    <div style={{
                      fontSize: '16px',
                      fontWeight: '600',
                      color: '#1f2937',
                      marginBottom: '8px',
                      lineHeight: '1.4'
                    }}>
                      {board.board_name || 'N/A'}
                    </div>
                    {board.relevant_acts && (
                      <div style={{
                        fontSize: '12px',
                        color: '#6b7280',
                        marginBottom: '8px',
                        lineHeight: '1.4',
                        display: '-webkit-box',
                        WebkitLineClamp: 2,
                        WebkitBoxOrient: 'vertical',
                        overflow: 'hidden'
                      }}>
                        <strong>Acts:</strong> {board.relevant_acts}
                      </div>
                    )}
                    {board.website && (
                      <div style={{
                        fontSize: '12px',
                        color: '#6b7280',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                        marginTop: '8px'
                      }}>
                        <i className="fas fa-globe" style={{color: '#10b981'}}></i>
                        <a
                          href={board.website.startsWith('http') ? board.website : `https://${board.website}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{
                            color: '#10b981',
                            textDecoration: 'none',
                            wordBreak: 'break-all'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.textDecoration = 'underline';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.textDecoration = 'none';
                          }}
                        >
                          {board.website}
                        </a>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Brochure Modal for Rank Finder Page */}
      <div id="brochureModal" className="brochure-modal" style={{display: 'none'}}>
        <div className="brochure-modal-content">
          <div className="brochure-modal-header">
            <h3 id="brochureModalTitle">
              <i className="fas fa-file-pdf me-2"></i>Notification Brochure
            </h3>
            <button className="brochure-close" onClick={closeBrochureModal}>&times;</button>
          </div>
          <div className="brochure-modal-body">
            <div id="brochureContent">
              <div className="brochure-loading">
                <i className="fas fa-spinner fa-spin me-2"></i>
                Loading brochure...
              </div>
            </div>
          </div>
          <div className="brochure-modal-footer">
            <button className="btn btn-secondary" onClick={closeBrochureModal}>
              <i className="fas fa-times me-2"></i>Close
            </button>
            <a id="brochureDownloadLink" className="btn btn-primary" target="_blank" rel="noopener noreferrer" style={{display: 'none'}}>
              <i className="fas fa-download me-2"></i>Download PDF
            </a>
          </div>
        </div>
      </div>
    </>
  );
}

function CoursesPage({ catalog, collegesByField, initialFilters }) {
  const [qualification, setQualification] = React.useState(initialFilters.qualification || '');
  const [stream, setStream] = React.useState(initialFilters.stream || '');
  const [level, setLevel] = React.useState(initialFilters.level || '');
  const [field, setField] = React.useState(initialFilters.field || '');
  const [exam, setExam] = React.useState(initialFilters.exam || '');
  const [college, setCollege] = React.useState(initialFilters.college || '');
  // Search functionality removed - use Rank Finder page instead
  const resultsRef = React.useRef(null);
  const [flash, setFlash] = React.useState(false);
  // Pagination for Course Catalog
  const [coursePage, setCoursePage] = React.useState(1);
  const [coursePageSize, setCoursePageSize] = React.useState(10);

  // Load admissions data for rounds on the Courses page
  const [admissions, setAdmissions] = React.useState(() => window.__admissionsData__ || null);
  React.useEffect(() => {
    if (!admissions) {
      fetch('api/admissions.php')
        .then(r => {
          if (r.ok) {
            return safeJsonParse(r);
          }
          return null;
        })
        .then(data => { if (data) { setAdmissions(data); window.__admissionsData__ = data; } })
        .catch(() => {});
    }
  }, []);
  const roundsRaw = admissions?.ug_engineering?.rounds || [];
  const rounds = React.useMemo(() => roundsRaw.map(r => ({
    id: r.id,
    name: r.name || (r.seq ? `Round-${r.seq}` : `Round-${r.id}`),
    status: r.status,
    application: { start: (r.application && r.application.start) || r.application_start || '', end: (r.application && r.application.end) || r.application_end || '' },
    merit_declaration: r.merit_declaration || r.merit_date || '',
    choice_filling: { start: (r.choice_filling && r.choice_filling.start) || r.choice_start || '', end: (r.choice_filling && r.choice_filling.end) || r.choice_end || '' },
    seat_allotment: r.seat_allotment || r.allotment_date || '',
    reporting: { start: (r.reporting && r.reporting.start) || r.reporting_start || '', end: (r.reporting && r.reporting.end) || r.reporting_end || '' },
  })), [roundsRaw]);

  // downloadEligibilityPdf function removed - use Rank Finder page instead

  // Search-related functions removed - use Rank Finder page instead

  // collegesByField is provided via props

  // Full option lists regardless of selection; filtering applies only after selection
  const allFields = React.useMemo(() => Array.from(new Set(catalog.map(c => c.field))).sort(), [catalog]);
  const allLevels = React.useMemo(() => Array.from(new Set(catalog.map(c => c.level))).sort(), [catalog]);
  const allExams = React.useMemo(() => Array.from(new Set(catalog.flatMap(c => c.exams))).filter(Boolean).sort(), [catalog]);
  const allColleges = React.useMemo(() => {
    const out = new Set();
    Object.values(collegesByField).forEach(list => list.forEach(name => out.add(name)));
    return Array.from(out).sort();
  }, [collegesByField]);

  const filteredCatalog = React.useMemo(() => {
    const norm = (s) => (s || '').toString().trim().toLowerCase();
    const qualificationNorm = norm(qualification);
    const streamNorm = norm(stream);
    const levelNorm = norm(level);
    const fieldNorm = norm(field);
    const examNorm = norm(exam);
    const collegeNorm = norm(college);
    const list = catalog.filter(item => {
      const itemEligibility = norm(item.eligibility);
      const itemLevel = norm(item.level);
      const itemField = norm(item.field);
      const itemStream = norm(item.stream);
      const itemExams = Array.isArray(item.exams) ? item.exams.map(norm) : [];

      // Qualification mapping: 10th -> Diploma, 12th -> UG, UG -> PG
      if (qualificationNorm) {
        const qualToLevels = {
          '10th': ['diploma'],
          '12th': ['ug'],
          'ug': ['pg']
        };
        const allowedLevels = qualToLevels[qualificationNorm] || [];
        const eligibleByLevel = allowedLevels.length === 0 || allowedLevels.includes(itemLevel);
        const eligibleByFlag = (qualificationNorm === '12th' && (itemEligibility === 'ug' || itemEligibility.includes('12')))
          || (qualificationNorm === '10th' && (itemEligibility.includes('10')))
          || (qualificationNorm === 'ug' && (itemEligibility === 'pg' || itemEligibility.includes('bachelor') || itemEligibility.includes('ug')));
        if (!(eligibleByLevel || eligibleByFlag)) return false;
        // Stream restriction (only applies for 12th)
        if (qualificationNorm === '12th' && streamNorm) {
          if (itemStream && itemStream !== streamNorm) return false;
          // For items without explicit stream, allow common cross-stream UG programs like BBA/B.Com/B.A.
          if (!itemStream && streamNorm && ['commerce','arts'].includes(streamNorm)) {
            const name = norm(item.name);
            const cross = ['bba','b.com','b.a','bca'];
            if (!cross.some(k => name.includes(k))) {
              // Keep engineering/pharmacy etc out when choosing non-science stream
              if (['engineering','pharmacy','architecture','it','computer'].some(k => name.includes(k))) return false;
            }
          }
        }
      }

      if (levelNorm && itemLevel !== levelNorm) return false;
      if (fieldNorm && itemField !== fieldNorm) return false;
      if (examNorm && !itemExams.includes(examNorm)) return false;
      if (collegeNorm) {
        const pool = (collegesByField[item.field] || []).map(norm);
        if (!pool.includes(collegeNorm)) return false;
      }
      return true;
    });
    // Rank/percentage based soft ordering using available cutoffs from admissions (loaded on Home)
    let sorted = list.slice();
    const r = parseInt(rank, 10);
    const p = parseFloat(percent);
    if (!isNaN(r) || !isNaN(p) || cityScope !== 'any' || homeCity) {
      // Fetch admissions cutoffs from window (HomeSections stores it on window for reuse)
      const admissions = window.__admissionsData__;
      const cutoffs = admissions?.ug_engineering?.cutoffs || [];
      const byCourse = new Map();
      cutoffs.forEach(co => {
        const key = (co.course || '').toLowerCase();
        if (!byCourse.has(key)) byCourse.set(key, []);
        byCourse.get(key).push(co);
      });
      sorted.sort((a, b) => {
        const ak = (a.name || '').toLowerCase();
        const bk = (b.name || '').toLowerCase();
        const aCut = byCourse.get(ak) || [];
        const bCut = byCourse.get(bk) || [];
        const aScore = scoreCourse(aCut, r, p, homeCity, cityScope);
        const bScore = scoreCourse(bCut, r, p, homeCity, cityScope);
        return bScore - aScore;
      });
    }
    return sorted;
  }, [catalog, qualification, stream, level, field, exam, college, collegesByField, rank, percent, homeCity, cityScope]);

  // Reset Course Catalog pagination on relevant filter changes
  React.useEffect(() => {
    setCoursePage(1);
  }, [qualification, stream, level, field, exam, college, catalog.length]);

  // runEligibilitySearch function removed - use Rank Finder page instead

  return (
    <div className="professional-courses-page">
      {/* Professional Header */}
      <div className="page-header-section">
        <div className="container">
          <div className="page-header-content">
            <h1 className="page-title">Available Courses</h1>
            <p className="page-description">
              Comprehensive course catalog with detailed information about eligibility, duration, and entrance requirements
            </p>
          </div>
        </div>
      </div>

      <div className="main-content">
        <div className="container">
          <div className="content-layout" style={{gridTemplateColumns:'1fr'}}>

            {/* Search functionality removed - use Rank Finder page instead */}
            
              {/* Course Filters */}
              <div className="filters-widget">
                <div className="widget-header">
                  <h3>Filter Courses</h3>
                </div>
                <div className="widget-content">
                  <div className="form-grid">
                    <div className="form-field">
                      <label>Qualification</label>
                      <select value={qualification} onChange={e => { setQualification(e.target.value); setStream(''); }}>
                        <option value="">Any</option>
                        <option value="10th">10th Standard</option>
                        <option value="12th">12th Standard</option>
                        <option value="UG">Graduation</option>
                      </select>
                    </div>
                    <div className="form-field">
                      <label>Stream</label>
                      <select value={stream} onChange={e => setStream(e.target.value)}>
                        <option value="">Any</option>
                        <option value="Science">Science</option>
                        <option value="Commerce">Commerce</option>
                        <option value="Arts">Arts</option>
                      </select>
                    </div>
                    <div className="form-field">
                      <label>Level</label>
                      <select value={level} onChange={e => setLevel(e.target.value)}>
                        <option value="">Any</option>
                        {allLevels.map(l => <option key={l} value={l}>{l}</option>)}
                      </select>
                    </div>
                    <div className="form-field">
                      <label>Field</label>
                      <select value={field} onChange={e => setField(e.target.value)}>
                        <option value="">Any</option>
                        {allFields.map(f => <option key={f} value={f}>{f}</option>)}
                      </select>
                    </div>
                    <div className="form-field">
                      <label>College</label>
                      <select value={college} onChange={e => setCollege(e.target.value)}>
                        <option value="">Any</option>
                        {allColleges.map(c => <option key={c} value={c}>{c}</option>)}
                      </select>
                    </div>
                    <div className="form-field">
                      <label>Entrance Exam</label>
                      <select value={exam} onChange={e => setExam(e.target.value)}>
                        <option value="">Any</option>
                        {allExams.map(ex => <option key={ex} value={ex}>{ex}</option>)}
                      </select>
                    </div>
                  </div>
                  
                  {/* Search field removed - use Rank Finder page instead */}

                  {/* Active Filters */}
                  {(qualification || stream || level || field || exam || college) && (
                    <div className="active-filters">
                      <div className="filters-label">Active Filters:</div>
                      <div className="filter-tags">
                        {qualification && (
                          <span className="filter-tag">
                            {qualification}
                            <button onClick={() => setQualification('')}>×</button>
                          </span>
                        )}
                        {stream && (
                          <span className="filter-tag">
                            {stream}
                            <button onClick={() => setStream('')}>×</button>
                          </span>
                        )}
                        {level && (
                          <span className="filter-tag">
                            {level}
                            <button onClick={() => setLevel('')}>×</button>
                          </span>
                        )}
                        {field && (
                          <span className="filter-tag">
                            {field}
                            <button onClick={() => setField('')}>×</button>
                          </span>
                        )}
                        {college && (
                          <span className="filter-tag">
                            {college}
                            <button onClick={() => setCollege('')}>×</button>
                          </span>
                        )}
                        {exam && (
                          <span className="filter-tag">
                            {exam}
                            <button onClick={() => setExam('')}>×</button>
                          </span>
                        )}
                      </div>
                      <button 
                        className="clear-filters" 
                        onClick={() => { 
                          setQualification(''); 
                          setStream(''); 
                          setLevel(''); 
                          setField(''); 
                          setExam(''); 
                          setCollege(''); 
                        }}
                      >
                        Clear All
                      </button>
                    </div>
                  )}
                  
                  <div className="results-count">
                    <strong>{filteredCatalog.length}</strong> courses found
                  </div>
                </div>
              </div>

            {/* Main Content Area */}
            <main className="main-section">
              {/* Courses Table */}
              <div className="courses-table-section">
                <div className="section-header">
                  <h2>Course Catalog</h2>
                  <div className="section-info">
                    Browse through all available courses and their details
                  </div>
                </div>
                {/* Catalog Pagination Controls - Top */}
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'0.5rem 0'}}>
                  <div>
                    <label style={{marginRight:6}}>Rows per page</label>
                    <select value={coursePageSize} onChange={e=>{ setCoursePageSize(parseInt(e.target.value,10)||10); setCoursePage(1); }}>
                      {[10,25,50,100].map(n => <option key={n} value={n}>{n}</option>)}
                    </select>
                  </div>
                  {(() => {
                    const total = filteredCatalog.length;
                    const totalPages = Math.max(1, Math.ceil(total / coursePageSize));
                    return (
                      <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
                        <span>Page {coursePage} / {totalPages}</span>
                        <button className="btn" onClick={()=>setCoursePage(1)} disabled={coursePage===1}>«</button>
                        <button className="btn" onClick={()=>setCoursePage(p=>Math.max(1,p-1))} disabled={coursePage===1}>‹</button>
                        <button className="btn" onClick={()=>setCoursePage(p=>{
                          const tp = Math.max(1, Math.ceil(total / coursePageSize));
                          return Math.min(tp, p+1);
                        })} disabled={coursePage>=Math.max(1, Math.ceil(total / coursePageSize))}>›</button>
                        <button className="btn" onClick={()=>setCoursePage(Math.max(1, Math.ceil(total / coursePageSize)))} disabled={coursePage>=Math.max(1, Math.ceil(filteredCatalog.length / coursePageSize))}>»</button>
                      </div>
                    );
                  })()}
                </div>
                
                <div className="table-wrapper">
                  <table className="professional-table">
                    <thead>
                      <tr>
                        <th>Course Name</th>
                        <th>Level</th>
                        <th>Field</th>
                        <th>Duration</th>
                        <th>Eligibility</th>
                        <th>Exams</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredCatalog.length === 0 ? (
                        <tr>
                          <td colSpan="6">
                            <div className="no-results">
                              <i className="fas fa-search"></i>
                              <h4>No courses found</h4>
                              <p>Try adjusting your filters or clearing them to see more results.</p>
                            </div>
                          </td>
                        </tr>
                      ) : (() => {
                        const total = filteredCatalog.length;
                        const startIdx = (coursePage - 1) * coursePageSize;
                        const endIdx = startIdx + coursePageSize;
                        const visible = filteredCatalog.slice(startIdx, endIdx);
                        return visible.map(item => (
                          <tr key={item.id}>
                            <td className="course-name">
                              <a href={`#${item.sectionId}`}>{item.name}</a>
                            </td>
                            <td>{item.level}</td>
                            <td>{item.field}</td>
                            <td>{`${inferDisplayDuration(item.name, item.level, item.field, item.durationYears)} Years`}</td>
                            <td>{item.eligibility}{item.stream ? ` (${item.stream})` : ''}</td>
                            <td>{item.exams.length ? item.exams.join(', ') : '—'}</td>
                          </tr>
                        ));
                      })()}
                    </tbody>
                  </table>
                </div>
                {/* Catalog Pagination Controls - Bottom */}
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'0.75rem 0'}}>
                  <div>{filteredCatalog.length.toLocaleString()} results</div>
                  {(() => {
                    const total = filteredCatalog.length;
                    const totalPages = Math.max(1, Math.ceil(total / coursePageSize));
                    return (
                      <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
                        <button className="btn" onClick={()=>setCoursePage(1)} disabled={coursePage===1}>« First</button>
                        <button className="btn" onClick={()=>setCoursePage(p=>Math.max(1,p-1))} disabled={coursePage===1}>‹ Prev</button>
                        <span>Page {coursePage} of {totalPages}</span>
                        <button className="btn" onClick={()=>setCoursePage(p=>Math.min(totalPages,p+1))} disabled={coursePage===totalPages}>Next ›</button>
                        <button className="btn" onClick={()=>setCoursePage(totalPages)} disabled={coursePage===totalPages}>Last »</button>
                      </div>
                    );
                  })()}
                </div>
              </div>

              {/* Eligibility search removed - use Rank Finder page instead */}

              {/* Admission Timeline */}
              <div className="timeline-section">
                <div className="section-header">
                  <h2>Admission Timeline</h2>
                  <div className="section-info" style={{display:'flex',gap:'8px',flexWrap:'wrap',alignItems:'center'}}>
                    <span>Important dates and deadlines for admission rounds</span>
                    {(() => { const vac = rounds.find(r => (r.name||'').toLowerCase().includes('vacant')); if (!vac) return null; return (
                      <>
                        <button className="btn btn-primary" onClick={(e)=>{e.preventDefault(); try { const els = document.querySelectorAll('.timeline-item'); const idx = rounds.findIndex(x => (x.name||'').toLowerCase().includes('vacant')); if (els[idx]) els[idx].scrollIntoView({behavior:'smooth',block:'start'}); } catch(_){} }}><i className="fas fa-eye me-1"></i>View Vacant</button>
                        <button className="btn btn-danger" onClick={(e)=>{e.preventDefault(); downloadRoundPdf(vac.id, vac.name);}}><i className="fas fa-file-pdf me-1"></i>Vacant PDF</button>
                      </>
                    ); })()}
                  </div>
                </div>
                
                <div className="timeline-container">
                  {rounds.map(r => (
                    <div key={r.id} className={`timeline-item ${r.status?.toLowerCase() || ''}`}>
                      <div className="timeline-header">
                        <div className="timeline-title">{r.name}</div>
                        <div className={`timeline-status ${r.status?.toLowerCase() || ''}`}>{r.status}</div>
                      </div>
                      <div className="timeline-content">
                        <div className="timeline-grid">
                          <div className="timeline-event">
                            <strong>Application Period</strong>
                            <span>{r.application.start} → {r.application.end}</span>
                          </div>
                          <div className="timeline-event">
                            <strong>Merit Declaration</strong>
                            <span>{r.merit_declaration}</span>
                          </div>
                          <div className="timeline-event">
                            <strong>Choice Filling</strong>
                            <span>{r.choice_filling.start} → {r.choice_filling.end}</span>
                          </div>
                          <div className="timeline-event">
                            <strong>Seat Allotment</strong>
                            <span>{r.seat_allotment}</span>
                          </div>
                          <div className="timeline-event">
                            <strong>Reporting Period</strong>
                            <span>{r.reporting.start} → {r.reporting.end}</span>
                          </div>
                          <div className="timeline-event">
                            <strong>Download Round</strong>
                            <span style={{display:'flex',gap:'8px',flexWrap:'wrap'}}>
                              <button className="btn btn-danger" onClick={(e)=>{e.preventDefault(); downloadRoundPdf(r.id, r.name);}}><i className="fas fa-file-pdf me-1"></i>PDF</button>
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                  {rounds.length === 0 && (
                    <div className="no-results">
                      <i className="fas fa-calendar-alt"></i>
                      <h4>No admission rounds available</h4>
                      <p>Check back later for updated admission timeline.</p>
                    </div>
                  )}
                </div>
              </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  );
}
function scoreCourse(courseCutoffs, rank, percent, homeCity, cityScope) {
  // Higher score is better match
  let score = 0;
  // Basic closeness by rank (lower closing rank is more competitive)
  if (!isNaN(rank)) {
    const best = Math.min(...courseCutoffs.map(co => parseInt(co.closing_rank, 10)).filter(n => !isNaN(n)), Infinity);
    if (best !== Infinity) {
      // If user's rank is better than or close to best closing rank, bump
      if (rank <= best) score += 50;
      const diff = Math.abs(rank - best);
      score += Math.max(0, 30 - Math.log10(diff + 1) * 10);
    }
  }
  // Percentage heuristic (if present)
  if (!isNaN(percent)) {
    score += Math.min(20, Math.max(0, (percent - 50))); // small boost for higher %
  }
  // City preference
  if (homeCity && cityScope !== 'any') {
    const anyCity = (arr, city) => arr.some(co => (co.city || '').toLowerCase() === city.toLowerCase());
    const hasHome = anyCity(courseCutoffs, homeCity);
    if (cityScope === 'within') score += hasHome ? 20 : -20;
    if (cityScope === 'outside') score += hasHome ? -20 : 10;
  }
  return score;
}

// Unused search function removed - use Rank Finder page instead

// Simple hash router and data loader
function useHashRoute() {
  const [route, setRoute] = React.useState(window.location.hash || '#/');
  React.useEffect(() => {
    const onChange = () => setRoute(window.location.hash || '#/');
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  return route;
}

function parseHashParams(hash) {
  const idx = hash.indexOf('?');
  if (idx === -1) return {};
  const query = hash.slice(idx + 1);
  const params = new URLSearchParams(query);
  return {
    q: params.get('q') || '',
    qualification: params.get('qualification') || '',
    stream: params.get('stream') || '',
    level: params.get('level') || '',
    field: params.get('field') || '',
    exam: params.get('exam') || '',
    college: params.get('college') || '',
  };
}

function HomePage() {
  const [homeQuery, setHomeQuery] = React.useState('');
  const goToCourses = (extra = {}) => {
    const params = new URLSearchParams();
    if (homeQuery.trim()) params.set('q', homeQuery.trim());
    Object.entries(extra).forEach(([k, v]) => { if (v) params.set(k, v); });
    window.location.hash = `#/courses?${params.toString()}`;
  };
  return (
    <HomeSections />
  );
}

// Brochure modal functions
function openNotificationBrochure(notification, index) {
  console.log('Opening brochure for notification:', notification);
  
  // Set modal title
  document.getElementById('brochureModalTitle').innerHTML = 
    `<i className="fas fa-file-pdf me-2"></i>${notification.title}`;
  
  // Show modal
  document.getElementById('brochureModal').style.display = 'flex';
  
  // Load brochure content
  loadBrochureContent(notification, index);
}

function closeBrochureModal() {
  document.getElementById('brochureModal').style.display = 'none';
  document.getElementById('brochureContent').innerHTML = 
    '<div className="brochure-loading"><i className="fas fa-spinner fa-spin me-2"></i>Loading brochure...</div>';
}

function loadBrochureContent(notification, index) {
  const contentDiv = document.getElementById('brochureContent');
  const downloadLink = document.getElementById('brochureDownloadLink');
  
  // Check if notification has brochure
  if (notification.brochure_file) {
    // Show PDF embed
    contentDiv.innerHTML = `
      <div className="brochure-pdf-container">
        <iframe 
          src="${notification.brochure_file}" 
          width="100%" 
          height="500px"
          style="border: none; border-radius: 8px;"
          title="${notification.title}">
        </iframe>
      </div>
    `;
    
    // Set download link
    downloadLink.href = notification.brochure_file;
    downloadLink.style.display = 'inline-block';
  } else {
    // Show notification detail page content
    contentDiv.innerHTML = `
      <div className="brochure-info">
        <div className="brochure-header">
          <h4>${notification.title}</h4>
          <p className="brochure-date">
            <i className="fas fa-calendar-alt me-2"></i>${notification.date}
          </p>
        </div>
        <div className="brochure-description">
          <p>This notification contains important information regarding the admission process. 
          Please read all details carefully and take necessary action as required.</p>
          ${notification.url && notification.url !== '#' ? 
            `<p><strong>External Link:</strong> <a href="${notification.url}" target="_blank" rel="noopener noreferrer">View Full Notification</a></p>` : 
            ''
          }
        </div>
        <div className="brochure-no-pdf">
          <i className="fas fa-info-circle me-2"></i>
          No brochure PDF available for this notification.
        </div>
      </div>
    `;
    
    // Hide download link
    downloadLink.style.display = 'none';
  }
}

function HomeSections() {
  const [admissions, setAdmissions] = React.useState(null);
  const [cutoffs2024, setCutoffs2024] = React.useState([]);
  // Last Admitted Rank data
  const [lastRankYear, setLastRankYear] = React.useState(2024);
  const [lastRankRows, setLastRankRows] = React.useState([]);
  const [lastRankLoading, setLastRankLoading] = React.useState(false);
  
  React.useEffect(() => {
    fetch('api/admissions.php')
      .then(safeJsonParse)
      .then(setAdmissions)
      .catch(() => setAdmissions(null));
    
    // Add click outside to close modal
    const handleClickOutside = (e) => {
      const modal = document.getElementById('brochureModal');
      if (modal && e.target === modal) {
        closeBrochureModal();
      }
    };
    
    // Add escape key to close modal
    const handleEscapeKey = (e) => {
      if (e.key === 'Escape') {
        const modal = document.getElementById('brochureModal');
        if (modal && modal.style.display === 'flex') {
          closeBrochureModal();
        }
      }
    };
    
    document.addEventListener('click', handleClickOutside);
    document.addEventListener('keydown', handleEscapeKey);
    
    return () => {
      document.removeEventListener('click', handleClickOutside);
      document.removeEventListener('keydown', handleEscapeKey);
    };
  }, []);
  // Removed: last year rounds (Round-1/2/3) section and its fetch
  React.useEffect(() => {
    fetch('api/admissions.php?year=2024')
      .then(r => {
        if (r.ok) {
          return safeJsonParse(r);
        }
        return null;
      })
      .then(data => setCutoffs2024(data?.ug_engineering?.cutoffs || []))
      .catch(() => setCutoffs2024([]));
  }, []);
  // Load last admitted rank data
  React.useEffect(() => {
    let cancelled = false;
    setLastRankLoading(true);
    fetch('api/last_admitted_rank.php?format=json&year=' + encodeURIComponent(lastRankYear))
      .then(r => {
        if (r.ok) {
          return safeJsonParse(r);
        }
        return [];
      })
      .then(rows => {
        if (!cancelled) {
          // Check if response is an error object
          if (rows && typeof rows === 'object' && !Array.isArray(rows) && rows.error) {
            console.error('Last admitted rank API error:', rows.error);
            alert('Error loading last admitted rank data: ' + rows.error);
            setLastRankRows([]);
          } else {
            const data = Array.isArray(rows) ? rows : [];
            console.log('Last admitted rank loaded:', data.length, 'rows for year', lastRankYear);
            if (data.length > 0) {
              console.log('Sample row:', data[0]);
            }
            setLastRankRows(data);
          }
        }
      })
      .catch(err => {
        if (!cancelled) {
          console.error('Failed to fetch last admitted rank:', err);
          setLastRankRows([]);
        }
      })
      .finally(() => { if (!cancelled) setLastRankLoading(false); });
    return () => { cancelled = true; };
  }, [lastRankYear]);

  const scheme = admissions?.scheme || 'Admissions';
  const ug = admissions?.ug_engineering;
  const roundsRaw = ug?.rounds || [];
  const notifications = ug?.notifications || [];
  const seatMatrix = ug?.seat_matrix || [];
  const cutoffs = ug?.cutoffs || [];
  
  // Load round-wise details from cutoff and allotment tables
  const [roundDetails, setRoundDetails] = React.useState([]);
  React.useEffect(() => {
    fetch('api/round_details.php')
      .then(r => {
        if (r.ok) {
          return safeJsonParse(r);
        }
        return [];
      })
      .then(data => setRoundDetails(data))
      .catch(() => setRoundDetails([]));
  }, []);
  // Pagination for Sample Cut-offs
  const [cutPage, setCutPage] = React.useState(1);
  const [cutPageSize, setCutPageSize] = React.useState(10);
  const cutTotal = cutoffs.length;
  const cutPages = Math.max(1, Math.ceil(cutTotal / cutPageSize));
  const cutStart = (cutPage - 1) * cutPageSize;
  const cutEnd = cutStart + cutPageSize;
  const cutVisible = cutoffs.slice(cutStart, cutEnd);
  // Normalize rounds to expected nested structure
  const rounds = React.useMemo(() => roundsRaw.map(r => ({
    id: r.id,
    name: r.name,
    status: r.status,
    application: { start: (r.application && r.application.start) || r.application_start || '', end: (r.application && r.application.end) || r.application_end || '' },
    merit_declaration: r.merit_declaration || r.merit_date || '',
    choice_filling: { start: (r.choice_filling && r.choice_filling.start) || r.choice_start || '', end: (r.choice_filling && r.choice_filling.end) || r.choice_end || '' },
    seat_allotment: r.seat_allotment || r.allotment_date || '',
    reporting: { start: (r.reporting && r.reporting.start) || r.reporting_start || '', end: (r.reporting && r.reporting.end) || r.reporting_end || '' },
  })), [roundsRaw]);
  React.useEffect(() => { if (admissions) window.__admissionsData__ = admissions; }, [admissions]);

  // Pagination for Last Admitted Rank
  const [lastRankPage, setLastRankPage] = React.useState(1);
  const [lastRankPageSize, setLastRankPageSize] = React.useState(20);
  const lastRankTotal = lastRankRows.length;
  const lastRankPages = Math.max(1, Math.ceil(lastRankTotal / lastRankPageSize));
  const lastRankStart = (lastRankPage - 1) * lastRankPageSize;
  const lastRankEnd = lastRankStart + lastRankPageSize;
  const lastRankVisible = lastRankRows.slice(lastRankStart, lastRankEnd);
  React.useEffect(() => { setLastRankPage(1); }, [lastRankYear, lastRankRows]);

  // Pagination for Cut-offs (2024)
  const [cut24Page, setCut24Page] = React.useState(1);
  const [cut24PageSize, setCut24PageSize] = React.useState(25);
  const cut24Total = cutoffs2024.length;
  const cut24Pages = Math.max(1, Math.ceil(cut24Total / cut24PageSize));
  const cut24Start = (cut24Page - 1) * cut24PageSize;
  const cut24End = cut24Start + cut24PageSize;
  const cut24Visible = cutoffs2024.slice(cut24Start, cut24End);
  React.useEffect(() => { setCut24Page(1); }, [cutoffs2024]);

  return (
    <>
      <div className="home-hero">
        {/* Decorative floating shapes */}
        <div style={{
          position: 'absolute',
          top: '10%',
          left: '10%',
          width: '100px',
          height: '100px',
          background: 'rgba(255, 255, 255, 0.1)',
          borderRadius: '50%',
          filter: 'blur(40px)',
          animation: 'float 15s ease-in-out infinite',
          zIndex: 1
        }}></div>
        <div style={{
          position: 'absolute',
          bottom: '15%',
          right: '15%',
          width: '150px',
          height: '150px',
          background: 'rgba(255, 255, 255, 0.08)',
          borderRadius: '50%',
          filter: 'blur(50px)',
          animation: 'float 20s ease-in-out infinite reverse',
          zIndex: 1
        }}></div>
        <div style={{
          position: 'absolute',
          top: '50%',
          right: '10%',
          width: '80px',
          height: '80px',
          background: 'rgba(255, 255, 255, 0.1)',
          borderRadius: '30%',
          transform: 'rotate(45deg)',
          filter: 'blur(30px)',
          animation: 'float 12s ease-in-out infinite',
          zIndex: 1
        }}></div>
        
        <div className="container hero-inner">
          <div className="hero-icon animate-fade-in" style={{
            fontSize: '90px',
            marginBottom: '2rem',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            width: '160px',
            height: '160px',
            margin: '0 auto 2rem',
            background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.1))',
            borderRadius: '50%',
            backdropFilter: 'blur(20px)',
            WebkitBackdropFilter: 'blur(20px)',
            boxShadow: '0 10px 40px rgba(0, 0, 0, 0.25), 0 0 60px rgba(255, 255, 255, 0.1), inset 0 0 30px rgba(255, 255, 255, 0.3)',
            border: '3px solid rgba(255, 255, 255, 0.4)',
            position: 'relative',
            zIndex: 2,
            animation: 'iconPulse 3s ease-in-out infinite',
            transition: 'transform 0.3s ease, box-shadow 0.3s ease',
            overflow: 'hidden'
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'scale(1.1) rotate(5deg)';
            e.currentTarget.style.boxShadow = '0 15px 50px rgba(0, 0, 0, 0.3), 0 0 80px rgba(255, 255, 255, 0.15), inset 0 0 40px rgba(255, 255, 255, 0.4)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'scale(1) rotate(0deg)';
            e.currentTarget.style.boxShadow = '0 10px 40px rgba(0, 0, 0, 0.25), 0 0 60px rgba(255, 255, 255, 0.1), inset 0 0 30px rgba(255, 255, 255, 0.3)';
          }}>
            {/* Shine effect overlay */}
            <div style={{
              position: 'absolute',
              top: '-50%',
              left: '-50%',
              width: '200%',
              height: '200%',
              background: 'linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.3) 50%, transparent 70%)',
              animation: 'shine 4s ease-in-out infinite',
              pointerEvents: 'none'
            }}></div>
            <i className="fas fa-graduation-cap" style={{
              color: 'white',
              filter: 'drop-shadow(0 4px 12px rgba(0, 0, 0, 0.4))',
              animation: 'iconFloat 4s ease-in-out infinite',
              position: 'relative',
              zIndex: 1
            }}></i>
          </div>
          <h1 className="hero-title animate-fade-in" style={{position: 'relative', zIndex: 2}}>
            Get My Admission
            <span style={{fontSize: '0.6em', fontWeight: 'normal', color: '#6b7280', marginLeft: '8px'}}>
              (Unofficial Tool)
            </span>
          </h1>
          <div className="hero-gradient animate-fade-in" style={{
            fontSize: '1.75rem', 
            fontWeight: '600', 
            marginTop: '1rem',
            position: 'relative',
            zIndex: 2,
            letterSpacing: '2px'
          }}>
            Plan • Apply • Succeed
          </div>
          <p className="hero-subtitle animate-fade-in" style={{position: 'relative', zIndex: 2}}>
            Empowering Dreams, Shaping Futures
          </p>
          <div className="hero-actions animate-fade-in">
            <button className="btn btn-primary" onClick={() => window.location.hash = '#/finder'}>
              <i className="fas fa-search me-2"></i>Explore Courses
            </button>
            <a className="btn btn-secondary" href="#/courses?qualification=12th&level=UG">
              <i className="fas fa-graduation-cap me-2"></i>I'm in 12th
            </a>
          </div>
          <div className="trust-strip animate-fade-in">
            <i className="fas fa-shield-alt me-2"></i>
            Trusted by 50,000+ applicants across Gujarat
          </div>
        </div>
      </div>

      {/* Highlights */}
      <div className="container home-highlights">
        <div className="row g-4">
          <div className="col-md-6 col-lg-3">
            <div className="highlight-card">
              <div className="highlight-icon">
                <i className="fas fa-search"></i>
              </div>
              <div className="highlight-title">Smart Search</div>
              <div className="highlight-desc">
                Advanced filtering by qualification, stream, city preference, and eligibility criteria.
              </div>
            </div>
          </div>
          <div className="col-md-6 col-lg-3">
            <div className="highlight-card">
              <div className="highlight-icon">
                <i className="fas fa-chart-line"></i>
              </div>
              <div className="highlight-title">Cut-off Insights</div>
              <div className="highlight-desc">
                Historical closing ranks and eligibility scores to help you make informed decisions.
              </div>
            </div>
          </div>
          <div className="col-md-6 col-lg-3">
            <div className="highlight-card">
              <div className="highlight-icon">
                <i className="fas fa-calendar-alt"></i>
              </div>
              <div className="highlight-title">Live Timeline</div>
              <div className="highlight-desc">
                Real-time admission rounds tracking with important dates and notifications.
              </div>
            </div>
          </div>
          <div className="col-md-6 col-lg-3">
            <div className="highlight-card">
              <div className="highlight-icon">
                <i className="fas fa-university"></i>
              </div>
              <div className="highlight-title">College Profiles</div>
              <div className="highlight-desc">
                Detailed college information with photos, courses, fees, and contact details.
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="container home-stats">
        <div className="row g-4">
          <div className="col-md-3 col-sm-6">
            <div className="stat-item">
              <div className="stat-value">1000+</div>
              <div className="stat-label">Programs</div>
            </div>
          </div>
          <div className="col-md-3 col-sm-6">
            <div className="stat-item">
              <div className="stat-value">200+</div>
              <div className="stat-label">Colleges</div>
            </div>
          </div>
          <div className="col-md-3 col-sm-6">
            <div className="stat-item">
              <div className="stat-value">10+</div>
              <div className="stat-label">Fields</div>
            </div>
          </div>
          <div className="col-md-3 col-sm-6">
            <div className="stat-item">
              <div className="stat-value">{(rounds.length || 4) + ''}</div>
              <div className="stat-label">Active Rounds</div>
            </div>
          </div>
        </div>
      </div>

      <div className="container home-sections">
        <section className="home-card">
          <div className="home-card-header">
            <h2>
              <i className="fas fa-calendar-alt me-2" style={{color: 'var(--primary)'}}></i>
              Admission Rounds Timeline
            </h2>
          </div>
          <div className="timeline">
            <div className="timeline-tools" style={{display:'flex',gap:'8px',marginBottom:'8px',alignItems:'center'}}>
              <button className="btn btn-danger" onClick={(e)=>{e.preventDefault(); downloadLastAdmittedRankPdf();}}>
                <i className="fas fa-file-pdf me-1"></i>Download Last Year Round Detail
              </button>
            </div>
            {roundDetails.length > 0 ? roundDetails.map(round => (
              <div key={round.round_id} className={`timeline-item ${round.status?.toLowerCase() || ''}`}>
                <div className="timeline-head">
                  <div className="badge">{round.round_name}</div>
                  <div className="status">{round.status || 'Active'}</div>
                </div>
                <div className="timeline-grid">
                  <div><strong>Application</strong><div>{round.application_start} → {round.application_end}</div></div>
                  <div><strong>Merit</strong><div>{round.merit_declaration}</div></div>
                  <div><strong>Choice Filling</strong><div>{round.choice_start} → {round.choice_end}</div></div>
                  <div><strong>Allotment</strong><div>{round.seat_allotment}</div></div>
                  <div><strong>Reporting</strong><div>{round.reporting_start} → {round.reporting_end}</div></div>
                  <div>
                    <strong>Round Statistics</strong>
                    <div style={{fontSize:'12px',marginTop:'4px'}}>
                      <div>Total Cutoffs: {round.total_cutoffs || 0}</div>
                      <div>Total Allotments: {round.total_allotments || 0}</div>
                      <div>Vacant Seats: {round.vacant_seats || 0}</div>
                    </div>
                  </div>
                  <div>
                    <strong>Download Round</strong>
                    <div style={{display:'flex',gap:'8px',flexWrap:'wrap',marginTop:4}}>
                      <button className="btn btn-danger" onClick={(e)=>{e.preventDefault(); downloadRoundPdf(round.round_id, round.round_name);}}>
                        <i className="fas fa-file-pdf me-1"></i>Cutoffs PDF
                      </button>
                      <button className="btn btn-success" onClick={(e)=>{e.preventDefault(); downloadStudentListPdf(round.round_id);}}>
                        <i className="fas fa-users me-1"></i>Student List
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )) : rounds.map(r => (
              <div key={r.id} className={`timeline-item ${r.status?.toLowerCase() || ''}`}>
                <div className="timeline-head">
                  <div className="badge">{r.name}</div>
                  <div className="status">{r.status}</div>
                </div>
                <div className="timeline-grid">
                  <div><strong>Application</strong><div>{r.application.start} → {r.application.end}</div></div>
                  <div><strong>Merit</strong><div>{r.merit_declaration}</div></div>
                  <div><strong>Choice Filling</strong><div>{r.choice_filling.start} → {r.choice_filling.end}</div></div>
                  <div><strong>Allotment</strong><div>{r.seat_allotment}</div></div>
                  <div><strong>Reporting</strong><div>{r.reporting.start} → {r.reporting.end}</div></div>
                <div>
                  <strong>Download Round</strong>
                  <div style={{display:'flex',gap:'8px',flexWrap:'wrap',marginTop:4}}>
                    <button className="btn btn-danger" onClick={(e)=>{e.preventDefault(); downloadRoundPdf(r.id, r.name);}}><i className="fas fa-file-pdf me-1"></i>PDF</button>
                  </div>
                </div>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* Removed: Last Year Rounds (2024) section */}
      
        <section className="home-card">
          <div className="home-card-header">
            <h2>
              <i className="fas fa-bell me-2" style={{color: 'var(--primary)'}}></i>
              Latest Notifications
            </h2>
          </div>
          {notifications.length > 0 ? (
            <div className="notice-grid">
              {notifications.map((n, i) => (
                <div 
                  key={i} 
                  className="notice-card" 
                  onClick={() => openNotificationBrochure(n, i)}
                  style={{cursor: 'pointer'}}
                >
                  <div className="notice-date-chip">
                    <i className="fas fa-calendar-alt me-1"></i>
                    {n.date}
                  </div>
                  <div className="notice-title">{n.title}</div>
                  <div style={{
                    marginTop: '0.5rem',
                    fontSize: '12px',
                    color: 'var(--gray)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.5rem'
                  }}>
                    <i className="fas fa-file-pdf"></i>
                    Click to view brochure
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div style={{
              textAlign: 'center',
              padding: '3rem',
              color: 'var(--gray)'
            }}>
              <i className="fas fa-bell-slash" style={{fontSize: '3rem', marginBottom: '1rem', opacity: 0.5}}></i>
              <p>No notifications available at the moment.</p>
              <p style={{fontSize: '14px', marginTop: '0.5rem'}}>Check back later for updates!</p>
            </div>
          )}
        </section>

        {/* Last Admitted Rank */}
        <section className="home-card">
          <div className="home-card-header" style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <h2>
              <i className="fas fa-table me-2" style={{color: 'var(--primary)'}}></i>
              Last Admitted Rank
            </h2>
            <div style={{display:'flex',gap:8,alignItems:'center'}}>
              <label>Year</label>
              <input type="number" min="2018" max={new Date().getFullYear()} value={lastRankYear} onChange={e=>setLastRankYear(parseInt(e.target.value,10)||lastRankYear)} style={{width:100}} />
            </div>
          </div>
          <div className="table-wrapper" style={{overflowX:'auto'}}>
            {lastRankLoading ? (
              <div style={{padding:'1rem'}}>Loading…</div>
            ) : lastRankRows.length === 0 ? (
              <div style={{padding:'1rem'}}>
                No data available for year {lastRankYear}. Please try selecting a different year.
                <br />
                <small style={{color:'#666'}}>Check browser console (F12) for details.</small>
              </div>
            ) : (
              <table className="courses-table">
                <thead>
                  <tr>
                    <th rowSpan="2">College</th>
                    <th rowSpan="2">Course</th>
                    <th colSpan="2">OPEN</th>
                    <th colSpan="2">SC</th>
                    <th colSpan="2">ST</th>
                    <th colSpan="2">SEBC</th>
                    <th colSpan="2">EWS</th>
                    <th colSpan="2">ESM</th>
                    <th colSpan="2">JEE</th>
                  </tr>
                  <tr>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>H Rank</th>
                    <th>Merit</th>
                    <th>Open AI Rank</th>
                    <th>TFWS AI Rank</th>
                  </tr>
                </thead>
                <tbody>
                  {lastRankVisible.map((r, i) => (
                    <tr key={i}>
                      <td>{r.college_name || '—'}</td>
                      <td>{r.course_name || '—'}</td>
                      <td>{r.open_hrank != null && r.open_hrank !== '' ? r.open_hrank : '—'}</td>
                      <td>{r.open_merit != null && r.open_merit !== '' ? r.open_merit : '—'}</td>
                      <td>{r.sc_hrank != null && r.sc_hrank !== '' ? r.sc_hrank : '—'}</td>
                      <td>{r.sc_merit != null && r.sc_merit !== '' ? r.sc_merit : '—'}</td>
                      <td>{r.st_hrank != null && r.st_hrank !== '' ? r.st_hrank : '—'}</td>
                      <td>{r.st_merit != null && r.st_merit !== '' ? r.st_merit : '—'}</td>
                      <td>{r.sebc_hrank != null && r.sebc_hrank !== '' ? r.sebc_hrank : '—'}</td>
                      <td>{r.sebc_merit != null && r.sebc_merit !== '' ? r.sebc_merit : '—'}</td>
                      <td>{r.ews_hrank != null && r.ews_hrank !== '' ? r.ews_hrank : '—'}</td>
                      <td>{r.ews_merit != null && r.ews_merit !== '' ? r.ews_merit : '—'}</td>
                      <td>{r.esm_hrank != null && r.esm_hrank !== '' ? r.esm_hrank : '—'}</td>
                      <td>{r.esm_merit != null && r.esm_merit !== '' ? r.esm_merit : '—'}</td>
                      <td>{r.jee_open_ai_rank != null && r.jee_open_ai_rank !== '' ? r.jee_open_ai_rank : '—'}</td>
                      <td>{r.jee_tfws_ai_rank != null && r.jee_tfws_ai_rank !== '' ? r.jee_tfws_ai_rank : '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
          {(lastRankTotal > 0) && (
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:'8px'}}>
              <div>{lastRankTotal.toLocaleString()} results</div>
              <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
                <label>Rows</label>
                <select value={lastRankPageSize} onChange={e=>{ setLastRankPageSize(parseInt(e.target.value,10)||20); setLastRankPage(1); }}>
                  {[10,20,50,100].map(n => <option key={n} value={n}>{n}</option>)}
                </select>
                <button className="btn" onClick={()=>setLastRankPage(1)} disabled={lastRankPage===1}>«</button>
                <button className="btn" onClick={()=>setLastRankPage(p=>Math.max(1,p-1))} disabled={lastRankPage===1}>‹</button>
                <span>Page {lastRankPage} / {lastRankPages}</span>
                <button className="btn" onClick={()=>setLastRankPage(p=>Math.min(lastRankPages,p+1))} disabled={lastRankPage===lastRankPages}>›</button>
                <button className="btn" onClick={()=>setLastRankPage(lastRankPages)} disabled={lastRankPage===lastRankPages}>»</button>
              </div>
            </div>
          )}
        </section>

        <section className="home-card">
          <div className="home-card-header">
            <h2>
              <i className="fas fa-chart-pie me-2" style={{color: 'var(--primary)'}}></i>
              Seat Matrix
            </h2>
          </div>
          <div className="table-wrapper">
            <table className="courses-table">
              <thead><tr><th>Field</th><th>Level</th><th>Seats</th></tr></thead>
              <tbody>
                {seatMatrix.map((s, i) => (
                  <tr key={i}><td>{s.field}</td><td>{s.level}</td><td>{s.seats.toLocaleString()}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
        {cutoffs2024.length > 0 && (
  <section className="home-card">
    <div className="home-card-header">
      <h2>
        <i className="fas fa-trophy me-2" style={{color: 'var(--primary)'}}></i>
        Cut-offs (2024)
      </h2>
    </div>
    <div className="table-wrapper">
      <table className="courses-table">
        <thead>
          <tr>
            <th>College</th>
            <th>Course</th>
            <th>Category</th>
            <th>Round</th>
            <th>Closing Rank</th>
          </tr>
        </thead>
        <tbody>
          {cut24Visible.map((c, i) => (
            <tr key={i}>
              <td>{c.college}</td>
              <td>{c.course}</td>
              <td>{c.category}</td>
              <td>{c.round}</td>
              <td>{c.closing_rank}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:'8px'}}>
      <div>{cut24Total.toLocaleString()} results</div>
      <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
        <label>Rows</label>
        <select value={cut24PageSize} onChange={e=>{ setCut24PageSize(parseInt(e.target.value,10)||25); setCut24Page(1); }}>
          {[10,25,50,100].map(n => <option key={n} value={n}>{n}</option>)}
        </select>
        <button className="btn" onClick={()=>setCut24Page(1)} disabled={cut24Page===1}>«</button>
        <button className="btn" onClick={()=>setCut24Page(p=>Math.max(1,p-1))} disabled={cut24Page===1}>‹</button>
        <span>Page {cut24Page} / {cut24Pages}</span>
        <button className="btn" onClick={()=>setCut24Page(p=>Math.min(cut24Pages,p+1))} disabled={cut24Page===cut24Pages}>›</button>
        <button className="btn" onClick={()=>setCut24Page(cut24Pages)} disabled={cut24Page===cut24Pages}>»</button>
      </div>
    </div>
  </section>
)}
        
        <section className="home-card">
          <div className="home-card-header">
            <h2>
              <i className="fas fa-trophy me-2" style={{color: 'var(--primary)'}}></i>
              Sample Cut-offs
            </h2>
          </div>
          <div className="table-wrapper">
            <table className="courses-table">
              <thead><tr><th>College</th><th>Course</th><th>Category</th><th>Round</th><th>Closing Rank</th></tr></thead>
              <tbody>
                {cutVisible.map((c, i) => (
                  <tr key={i}><td>{c.college}</td><td>{c.course}</td><td>{c.category}</td><td>{c.round}</td><td>{c.closing_rank}</td></tr>
                ))}
              </tbody>
            </table>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:'8px'}}>
              <div>{cutTotal.toLocaleString()} results</div>
              <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
                <label>Rows</label>
                <select value={cutPageSize} onChange={e=>{ setCutPageSize(parseInt(e.target.value,10)||10); setCutPage(1); }}>
                  {[10,25,50,100].map(n => <option key={n} value={n}>{n}</option>)}
                </select>
                <button className="btn" onClick={()=>setCutPage(1)} disabled={cutPage===1}>«</button>
                <button className="btn" onClick={()=>setCutPage(p=>Math.max(1,p-1))} disabled={cutPage===1}>‹</button>
                <span>Page {cutPage} / {cutPages}</span>
                <button className="btn" onClick={()=>setCutPage(p=>Math.min(cutPages,p+1))} disabled={cutPage===cutPages}>›</button>
                <button className="btn" onClick={()=>setCutPage(cutPages)} disabled={cutPage===cutPages}>»</button>
              </div>
            </div>
          </div>
        </section>
      </div>

      {/* CTA Banner */}
      <div className="home-cta">
        <div className="container home-cta-inner">
          <div className="home-cta-text">
            <h3>Ready to explore your options?</h3>
            <p>
              Join thousands of students who have found their perfect college match. 
              Start your journey to higher education today!
            </p>
          </div>
          <div className="home-cta-actions">
            <a className="btn btn-primary" href="#/courses">
              <i className="fas fa-search me-2"></i>Start Exploring
            </a>
            <a className="btn btn-secondary" href="#/courses?qualification=12th&level=UG">
              <i className="fas fa-graduation-cap me-2"></i>Find After 12th
            </a>
          </div>
        </div>
      </div>

      {/* Brochure Modal */}
      <div id="brochureModal" className="brochure-modal" style={{display: 'none'}}>
        <div className="brochure-modal-content">
          <div className="brochure-modal-header">
            <h3 id="brochureModalTitle">
              <i className="fas fa-file-pdf me-2"></i>Notification Brochure
            </h3>
            <button className="brochure-close" onClick={closeBrochureModal}>&times;</button>
          </div>
          <div className="brochure-modal-body">
            <div id="brochureContent">
              <div className="brochure-loading">
                <i className="fas fa-spinner fa-spin me-2"></i>
                Loading brochure...
              </div>
            </div>
          </div>
          <div className="brochure-modal-footer">
            <button className="btn btn-secondary" onClick={closeBrochureModal}>
              <i className="fas fa-times me-2"></i>Close
            </button>
            <a id="brochureDownloadLink" className="btn btn-primary" target="_blank" rel="noopener noreferrer">
              <i className="fas fa-download me-2"></i>Download PDF
            </a>
          </div>
        </div>
      </div>
    </>
  );
}
async function downloadRoundPdf(roundId, roundName) {
  try {
    const res = await fetch(`api/export_round.php?format=json&round_id=${roundId}`);
    if (!res.ok) throw new Error('Failed to load round data');
    const rows = await safeJsonParse(res);
    const head = [['College','Program','Category','Board','Open Rank','Closing Rank']];
    const body = rows.map(r => [
      r.college||'', 
      r.program||'', 
      r.category||'', 
      r.exam||'', 
      (r.open_rank && r.open_rank > 0) ? r.open_rank : '—', 
      (r.closing_rank && r.closing_rank > 0) ? r.closing_rank : '—'
    ]);
    const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation:'landscape', unit:'pt', format:'a4' });
  // Title styling: dark text on white background
  doc.setTextColor(34, 34, 34);
  doc.setFontSize(16);
  doc.text(`${roundName} Cut-offs`, 40, 40);
    doc.autoTable({ startY: 60, head, body, styles:{ fontSize:9 }, headStyles:{ fillColor:[37,99,235], textColor:[255,255,255], fontStyle:'bold', halign:'center' } });
    doc.save(`${roundName.replace(/\s+/g,'_')}_Cutoffs.pdf`);
  } catch (e) {
    alert('Unable to generate PDF for '+roundName);
  }
}

async function downloadLastYearMetricsPdf() {
  try {
    const year = new Date().getFullYear() - 1;
    const res = await fetch(`api/export_metrics.php?format=json&year=${year}`);
    if (!res.ok) throw new Error('Failed to load metrics');
    const rows = await safeJsonParse(res);
    // Build summary (scheme / year / round) from dataset
    const uniq = (arr) => Array.from(new Set(arr.filter(Boolean)));
    const schemes = uniq(rows.map(r => r.scheme_name));
    const years = uniq(rows.map(r => r.scheme_year));
    const rounds = uniq(rows.map(r => r.round_name));
    // Table should exclude scheme_name, scheme_year, round_name
    const head = [[
      'college_code','college_name','course_name','exam_name','category_code','metric','value'
    ]];
    const body = rows.map(r => [
      r.college_code||'', r.college_name||'',
      r.course_name||'', r.exam_name||'', r.category_code||'', r.metric||'', String(r.value ?? '')
    ]);
    const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation:'landscape', unit:'pt', format:'a4' });
  doc.setTextColor(34, 34, 34);
  doc.setFontSize(16);
  doc.text(`Cutoff Metrics ${year}`, 40, 40);
    // Summary line below title
    doc.setFontSize(11);
    const summary = `Scheme: ${schemes.join(', ') || '—'}  |  Year: ${years.join(', ') || '—'}  |  Round: ${rounds.join(', ') || '—'}`;
    doc.text(summary, 40, 58);
    // Table
    doc.autoTable({
      startY: 76,
      head,
      body,
      styles:{ fontSize:9, cellWidth:'wrap' },
      headStyles:{ fillColor:[37,99,235], textColor:[255,255,255], fontStyle:'bold', halign:'center' },
      columnStyles:{ 1:{ cellWidth:200 }, 2:{ cellWidth:170 } }
    });
    doc.save(`cutoff_metrics_${year}.pdf`);
  } catch (e) {
    alert('Unable to generate PDF');
  }
}

async function downloadLastAdmittedRankPdf() {
  try {
    const year = new Date().getFullYear() - 1;
    const url = `api/export_last_rank.php?format=json&year=${encodeURIComponent(year)}`;
    const res = await fetch(url);
    if (!res.ok) {
      const txt = await res.text().catch(() => '');
      throw new Error(`HTTP ${res.status}: ${txt || 'Failed to load last admitted rank'}`);
    }
    let rows;
    try { rows = await safeJsonParse(res); }
    catch (e) {
      const txt = await res.text().catch(() => '');
      throw new Error(`Invalid JSON from server. ${txt.slice(0,300)}`);
    }
    const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation:'landscape', unit:'pt', format:'a3' });
  // Strong brand header band + high-contrast title
  const pageWidth = doc.internal.pageSize.getWidth();
  doc.setFillColor(37, 99, 235); // brand blue
  doc.rect(0, 0, pageWidth, 72, 'F');
  doc.setTextColor(255, 255, 255);
  try { doc.setFont('helvetica', 'bold'); } catch (_) {}
  doc.setFontSize(20);
  doc.text(`Last Admitted Rank • A.Y. ${year}-${String(year+1).slice(-2)}`, 40, 46);

    const head = [[
      'Institute', 'Course',
      'GUJ OPEN H_Rank','GUJ OPEN Merit',
      'GUJ SC H_Rank','GUJ SC Merit',
      'GUJ ST H_Rank','GUJ ST Merit',
      'GUJ SEBC H_Rank','GUJ SEBC Merit',
      'GUJ EWS H_Rank','GUJ EWS Merit',
      'GUJ ESM H_Rank','GUJ ESM Merit',
      'JEE OPEN AI Rank','JEE TFWS AI Rank'
    ]];
    const body = rows.map(r => [
      r.institute_name || '', r.course || '',
      fmt(r.guj_open_hrank), fmt(r.guj_open_merit_marks),
      fmt(r.guj_sc_hrank),   fmt(r.guj_sc_merit_marks),
      fmt(r.guj_st_hrank),   fmt(r.guj_st_merit_marks),
      fmt(r.guj_sebc_hrank), fmt(r.guj_sebc_merit_marks),
      fmt(r.guj_ews_hrank),  fmt(r.guj_ews_merit_marks),
      fmt(r.guj_esm_hrank),  fmt(r.guj_esm_merit_marks),
      fmt(r.jee_open_last_rank), fmt(r.jee_tfws_last_rank)
    ]);
    function fmt(v){ return (v === null || v === undefined || v === '') ? '—' : String(v); }
    doc.autoTable({
      startY: 84,
      head,
      body,
      styles:{ fontSize:8, cellPadding:3 },
      headStyles:{ fillColor:[37,99,235], textColor:[255,255,255], fontStyle:'bold', halign:'center' },
      columnStyles:{ 0:{ cellWidth:220 }, 1:{ cellWidth:170 } }
    });
    doc.save(`last_admitted_rank_${year}.pdf`);
  } catch (e) {
    console.error(e);
    alert('Unable to generate Last Admitted Rank PDF: ' + (e && e.message ? e.message : 'unknown error'));
  }
}

async function downloadStudentListPdf(roundId = null) {
  try {
    const url = roundId ? `api/export_student_list.php?format=json&round_id=${roundId}` : 'api/export_student_list.php?format=json';
    const res = await fetch(url);
    if (!res.ok) {
      throw new Error('Failed to load student list data');
    }
    const rows = await safeJsonParse(res);
    
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF({ orientation:'landscape', unit:'pt', format:'a4' });
    
    // Header styling
    doc.setTextColor(34, 34, 34);
    doc.setFontSize(16);
    const title = roundId ? `Student Admission List - Round ${roundId}` : 'Student Admission List';
    doc.text(title, 40, 40);
    
    const head = [['Sr.No', 'Roll No', 'Student Name', 'College', 'Course', 'Category', 'Rank', 'Reporting Time']];
    const body = rows.map((r, i) => [
      i + 1,
      r.roll_no || '',
      r.applicant_name || '',
      r.college_name || '',
      r.course_name || '',
      r.category || '',
      r.vacant_seat_rank || '',
      r.time_of_reporting || ''
    ]);
    
    doc.autoTable({
      startY: 60,
      head,
      body,
      styles: { fontSize: 9 },
      headStyles: { fillColor: [37, 99, 235], textColor: [255, 255, 255], fontStyle: 'bold', halign: 'center' }
    });
    
    const filename = roundId ? `student_list_round_${roundId}.pdf` : 'student_admission_list.pdf';
    doc.save(filename);
  } catch (e) {
    alert('Unable to generate Student List PDF: ' + (e.message || 'unknown error'));
  }
}

function normalizeMetricName(s) {
  const t = String(s || '').trim().toUpperCase().replace(/\s+/g, '_');
  // Handle various forms of H Rank (including lowercase hrank from database)
  if ((t.includes('H') && t.includes('RANK')) || t === 'H_RANK' || t === 'HRANK' || t === 'H-RANK' || t === 'HRANK') {
    return 'H_RANK';
  }
  // Handle various forms of Merit Marks (including lowercase merit_marks from database)
  if ((t.includes('MERIT') && t.includes('MARK')) || t === 'MERIT_MARKS' || t === 'MERITMARKS' || t === 'MERIT-MARKS' || t === 'MERIT_MARK') {
    return 'MERIT_MARKS';
  }
  return t;
}

function pivotCutoffMetrics(rows) {
  const list = Array.isArray(rows) ? rows : [];
  const preferredCatOrder = ['OPEN','SC','ST','SEBC','EWS','ESM','TFWS'];
  const examsSet = new Set();
  const catsSet = new Set();
  const byKey = new Map();
  const metricNamesSeen = new Set(); // Debug: track metric names
  list.forEach(r => {
    const exam = (r.exam_name || '').toString();
    const cat = (r.category_code || '').toString().toUpperCase();
    const originalMetric = (r.metric || '').toString();
    const metric = normalizeMetricName(originalMetric);
    const value = r.value;
    if (!exam || !cat) return;
    metricNamesSeen.add(originalMetric); // Debug: track original metric names
    examsSet.add(exam);
    catsSet.add(cat);
    const key = (r.college_name || '') + '||' + (r.course_name || '');
    if (!byKey.has(key)) byKey.set(key, {
      college_name: r.college_name || '',
      course_name: r.course_name || '',
      values: {}
    });
    const row = byKey.get(key);
    if (!row.values[exam]) row.values[exam] = {};
    if (!row.values[exam][cat]) row.values[exam][cat] = {};
    // Store value, handling null/undefined/empty string (but allow 0 as valid)
    if (value != null && value !== '' && value !== 'null' && value !== 'NULL') {
      row.values[exam][cat][metric] = value;
      // Also store with original metric name as key (in case normalization doesn't match)
      row.values[exam][cat][originalMetric] = value;
    }
    // Also store the original metric name for debugging
    if (!row.values[exam][cat]._originalMetrics) {
      row.values[exam][cat]._originalMetrics = {};
    }
    row.values[exam][cat]._originalMetrics[originalMetric] = value;
  });
  // Debug: log metric names found
  if (metricNamesSeen.size > 0) {
    console.log('Metric names found in data:', Array.from(metricNamesSeen));
    console.log('Total rows processed:', list.length);
    console.log('Unique college-course combinations:', byKey.size);
    // Show sample of what was stored
    if (byKey.size > 0) {
      const firstKey = Array.from(byKey.keys())[0];
      const firstRow = byKey.get(firstKey);
      console.log('Sample stored structure:', {
        college: firstRow.college_name,
        course: firstRow.course_name,
        values: firstRow.values
      });
    }
  }
  const exams = Array.from(examsSet);
  // Order exams: GUJCET first, JEE next, then others
  exams.sort((a,b) => {
    const rank = (x) => x.toUpperCase() === 'GUJCET' ? 0 : (x.toUpperCase() === 'JEE' ? 1 : 2);
    const ra = rank(a), rb = rank(b);
    return ra === rb ? a.localeCompare(b) : ra - rb;
  });
  let categories = Array.from(catsSet);
  categories.sort((a,b) => {
    const ia = preferredCatOrder.indexOf(a);
    const ib = preferredCatOrder.indexOf(b);
    if (ia === -1 && ib === -1) return a.localeCompare(b);
    if (ia === -1) return 1;
    if (ib === -1) return -1;
    return ia - ib;
  });
  const rowsOut = Array.from(byKey.values()).sort((a,b) => {
    const ca = (a.college_name || '').localeCompare(b.college_name || '');
    if (ca !== 0) return ca;
    return (a.course_name || '').localeCompare(b.course_name || '');
  });
  return { exams, categories, rows: rowsOut };
}

function downloadMetricsPivotPdf(pivot, year) {
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation:'landscape', unit:'pt', format:'a3' });
  doc.setTextColor(34, 34, 34);
  doc.setFontSize(16);
  doc.text(`Cutoff Metrics ${year}`, 40, 40);
  const exams = pivot.exams || [];
  const cats = pivot.categories || [];
  // Build multi-row head with colSpans
  const headRow1 = [ { content:'College', rowSpan:3 }, { content:'Course', rowSpan:3 } ];
  exams.forEach(ex => headRow1.push({ content: ex, colSpan: cats.length * 2 }));
  const headRow2 = [];
  exams.forEach(ex => cats.forEach(cat => headRow2.push({ content: cat, colSpan: 2 })));
  const headRow3 = [];
  exams.forEach(ex => cats.forEach(cat => { headRow3.push('H Rank'); headRow3.push('Merit Marks'); }));
  // Body rows
  const body = (pivot.rows || []).map(r => {
    const arr = [r.college_name || '', r.course_name || ''];
    exams.forEach(ex => cats.forEach(cat => {
      const v = (r.values && r.values[ex] && r.values[ex][cat]) || {};
      arr.push(v && v.H_RANK != null && v.H_RANK !== '' ? String(v.H_RANK) : '—');
      arr.push(v && v.MERIT_MARKS != null && v.MERIT_MARKS !== '' ? String(v.MERIT_MARKS) : '—');
    }));
    return arr;
  });
  doc.autoTable({
    startY: 60,
    head: [headRow1, headRow2, headRow3],
    body,
    styles:{ fontSize:8, cellPadding:3 },
    headStyles:{ fillColor:[240,240,240] },
    columnStyles:{ 0:{ cellWidth:200 }, 1:{ cellWidth:160 } }
  });
  doc.save(`cutoff_metrics_pivot_${year}.pdf`);
}

function App() {
  const route = useHashRoute();
  const routePath = (route.split('?')[0] || '#/');
  const params = parseHashParams(route);

  const [catalog, setCatalog] = React.useState(defaultCatalog);
  
  // Make nav sticky below header
  React.useEffect(() => {
    const updateNavPosition = () => {
      const header = document.querySelector('.site-header');
      const nav = document.querySelector('.primary-nav');
      if (header && nav) {
        // Calculate header height and position nav below it
        const headerHeight = header.offsetHeight;
        nav.style.top = headerHeight + 'px';
      }
    };
    
    updateNavPosition();
    window.addEventListener('resize', updateNavPosition);
    // Also update after a short delay to ensure header is rendered
    setTimeout(updateNavPosition, 100);
    
    return () => {
      window.removeEventListener('resize', updateNavPosition);
    };
  }, []);
  const [collegesByField, setCollegesByField] = React.useState({
    Engineering: ['LD College of Engineering', 'VGEC', 'Nirma University', 'DAIICT'],
    Pharmacy: ['L.M. College of Pharmacy', 'Nirma Institute of Pharmacy'],
    Architecture: ['CEPT University'],
    Management: ['BK School of Management', 'Nirma Institute of Management'],
    IT: ['DAIICT', 'Nirma University'],
    Commerce: ['H.L. College of Commerce'],
    Arts: ["St. Xavier's College, Ahmedabad"],
  });

  // Scroll to top button state
  const [showScrollTop, setShowScrollTop] = React.useState(false);

  React.useEffect(() => {
    fetch('api/catalog.php')
      .then(safeJsonParse)
      .then(setCatalog)
      .catch(() => setCatalog([]));
    fetch('api/colleges.php')
      .then(safeJsonParse)
      .then(setCollegesByField)
      .catch(() => setCollegesByField({}));
  }, []);

  // Handle scroll to show/hide scroll-to-top button
  React.useEffect(() => {
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 300);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const [showDisclaimer, setShowDisclaimer] = React.useState(() => {
    // Check if user has dismissed the disclaimer
    return localStorage.getItem('disclaimerDismissed') !== 'true';
  });

  const dismissDisclaimer = () => {
    setShowDisclaimer(false);
    localStorage.setItem('disclaimerDismissed', 'true');
  };

  // Visit counter state
  const [visitStats, setVisitStats] = React.useState({
    total_visits: 0,
    today_visits: 0,
    unique_visitors: 0
  });

  // Track visit and load stats
  React.useEffect(() => {
    const trackVisit = async () => {
      try {
        // Track the visit
        const response = await fetch('api/track_visit.php?t=' + Date.now());
        const data = await safeJsonParse(response);
        if (data && data.total_visits !== undefined) {
          setVisitStats({
            total_visits: data.total_visits || 0,
            today_visits: data.today_visits || 0,
            unique_visitors: data.unique_visitors || 0
          });
        }
      } catch (error) {
        console.error('Failed to track visit:', error);
        // Try to get stats without tracking
        try {
          const statsResponse = await fetch('api/get_visit_stats.php?t=' + Date.now());
          const statsData = await safeJsonParse(statsResponse);
          if (statsData && statsData.total_visits !== undefined) {
            setVisitStats({
              total_visits: statsData.total_visits || 0,
              today_visits: statsData.today_visits || 0,
              unique_visitors: statsData.unique_visitors || 0
            });
          }
        } catch (statsError) {
          console.error('Failed to get visit stats:', statsError);
        }
      }
    };

    trackVisit();
  }, []);

  return (
    <div className="admission-portal-root">
      {/* Disclaimer Banner */}
      {showDisclaimer && (
        <div style={{
          background: 'linear-gradient(135deg, #fef3c7 0%, #fde68a 100%)',
          borderBottom: '2px solid #f59e0b',
          padding: '12px 0',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div className="container" style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: '1rem'
          }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '12px' }}>
              <span style={{ fontSize: '20px' }}>⚠️</span>
              <div style={{ flex: 1 }}>
                <strong style={{ color: '#92400e', fontSize: '14px', display: 'block', marginBottom: '2px' }}>
                  Important Notice - Testing/Development Site
                </strong>
                <p style={{ 
                  color: '#78350f', 
                  fontSize: '12px', 
                  margin: 0,
                  lineHeight: '1.4'
                }}>
                  This is a <strong>testing/development website</strong> created for educational and demonstration purposes. 
                  This site is <strong>NOT the official ACPC website</strong> and is not affiliated with, endorsed by, or connected to 
                  MY ADMISSION (ACPC) or the Government of Gujarat. 
                  All data, information, and results displayed are for <strong>testing purposes only</strong> and should not be used 
                  for making actual admission decisions. Please refer to the <strong>official ACPC website</strong> (
                  <a href="https://gujacpc.admissions.nic.in" target="_blank" rel="noopener" style={{ color: '#92400e', textDecoration: 'underline' }}>
                    gujacpc.admissions.nic.in
                  </a>) for accurate and official admission information.
                </p>
              </div>
            </div>
            <button
              onClick={dismissDisclaimer}
              style={{
                background: 'transparent',
                border: '1px solid #f59e0b',
                borderRadius: '4px',
                padding: '6px 12px',
                color: '#92400e',
                cursor: 'pointer',
                fontSize: '12px',
                fontWeight: '600',
                whiteSpace: 'nowrap',
                transition: 'all 0.2s'
              }}
              onMouseEnter={(e) => {
                e.target.style.background = '#f59e0b';
                e.target.style.color = 'white';
              }}
              onMouseLeave={(e) => {
                e.target.style.background = 'transparent';
                e.target.style.color = '#92400e';
              }}
            >
              Dismiss
            </button>
          </div>
        </div>
      )}
      <header className="site-header">
        <div className="container header-inner">
          <div className="branding">
            <div className="brand-emblem" aria-hidden="true">🛡️</div>
            <div className="brand-text">
              <div className="brand-title">Get My Admission <span style={{fontSize: '0.7em', fontWeight: 'normal', opacity: 0.8}}>(Unofficial)</span></div>
              <div className="brand-subtitle">Empowering Dreams, Shaping Futures</div>
            </div>
          </div>
          <div className="header-actions">
            {/* Search removed - use Rank Finder page instead */}
          </div>
        </div>
      </header>
      <nav className="primary-nav">
        <div className="container">
          <ul className="nav-list">
            <li><a href="#/" className={`nav-link ${routePath === '#/' ? 'active' : ''}`}>Home</a></li>
            <li><a href="#/finder" className={`nav-link ${routePath === '#/finder' ? 'active' : ''}`}>Rank Finder</a></li>
          </ul>
        </div>
      </nav>
      {routePath === '#/' && (<HomePage />)}
      {routePath === '#/courses' && (
        <>
          <div className="page-hero">
            <div className="container">
              <h1 className="page-title">Courses</h1>
              <div className="breadcrumbs">
                <a href="#/">Home</a> <span>/</span> <span>Courses</span>
              </div>
            </div>
          </div>
          <CoursesPage catalog={catalog} collegesByField={collegesByField} initialFilters={params} />
        </>
      )}
      {routePath === '#/finder' && (<RankFinderPage />)}
      <footer className="site-footer">
        <div className="container footer-inner">
          <div className="footer-left" style={{ flex: 1 }}>
            <div style={{ marginBottom: '8px' }}>
              © {new Date().getFullYear()} MY ADMISSION
            </div>
            <div style={{ 
              fontSize: '11px', 
              color: '#6b7280', 
              lineHeight: '1.5',
              maxWidth: '800px'
            }}>
              <strong>Disclaimer:</strong> This is a testing/development website for educational purposes only. 
              This site is NOT the official ACPC website and is not affiliated with, endorsed by, or connected to 
              MY ADMISSION (ACPC) or the Government of Gujarat. 
              All information displayed is for testing purposes only and should not be used for making actual admission decisions. 
              For official admission information, please visit the official ACPC website at{' '}
              <a href="https://gujacpc.admissions.nic.in" target="_blank" rel="noopener" style={{ color: '#2563eb' }}>
                gujacpc.admissions.nic.in
              </a>.
            </div>
          </div>
          <div className="footer-right">
            <a href="#">Terms</a>
            <span>•</span>
            <a href="#">Privacy</a>
          </div>
        </div>
      </footer>

      {/* Scroll to Top Button */}
      {showScrollTop && (
        <button
          onClick={scrollToTop}
          className="scroll-to-top"
          style={{
            opacity: showScrollTop ? 1 : 0,
            transform: showScrollTop ? 'translateY(0)' : 'translateY(20px)'
          }}
          aria-label="Scroll to top"
        >
          ↑
        </button>
      )}
    </div>
  );
}

// Helper to build filename-safe slugs from college names
function slugifyName(name) {
  return (name || '')
    .toLowerCase()
    .normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
    .replace(/&/g, ' and ')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .replace(/-+/g, '-');
}

// Renders a college photo with fallbacks: {slug}{1..3}.{jpg|jpeg|png|webp}
function CollegePhoto({ college, photo_url }) {
  const base = React.useMemo(() => slugifyName(college), [college]);
  const candidates = React.useMemo(() => {
    if (!base) return [];
    const seq = [1, 2, 3];
    const exts = ['.jpg', '.jpeg', '.png', '.webp'];
    const arr = [];
    seq.forEach(n => exts.forEach(ext => arr.push(`/uploads/colleges/${base}${n}${ext}`)));
    return arr;
  }, [base]);
  const [src, setSrc] = React.useState(photo_url || (candidates[0] || ''));
  const tried = React.useRef(new Set());
  React.useEffect(() => {
    tried.current = new Set();
    setSrc(photo_url || (candidates[0] || ''));
  }, [photo_url, base]);
  const onError = () => {
    const idx = candidates.findIndex(u => u === src);
    for (let i = idx + 1; i < candidates.length; i++) {
      if (!tried.current.has(candidates[i])) {
        tried.current.add(candidates[i]);
        setSrc(candidates[i]);
        return;
      }
    }
    setSrc('');
  };
  if (!base) return '—';
  return src
    ? <img 
        src={src} 
        alt={college} 
        onError={onError} 
        loading="lazy"
        style={{width:40,height:40,objectFit:'cover',borderRadius:4}} 
      />
    : '—';
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);




