'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import dynamic from 'next/dynamic';
import Pagination from '../../components/Pagination';
import Swal from 'sweetalert2';

const SummernoteEditor = dynamic(() => import('../../../components/organisms/SummernoteEditor'), { 
  ssr: false,
  loading: () => <p>Loading editor...</p>
});

// Updated tabs - added META & FAQ
const editTabs = [
  'GENERAL',
  'MORE DETAIL',
  'ENGLISH TESTS',
  'IMAGES',
  'ABOUT UNIVERSITY',
  'META & FAQ',
];

// University type options
const universityTypes = [
  { value: 'public', label: 'Public University' },
  { value: 'private', label: 'Private University' },
  { value: 'semi-government', label: 'Semi-Government University' }
];

// English test options
const englishTests = [
  { value: 'ielts', label: 'IELTS', maxScore: 9, step: 0.5, placeholder: 'e.g., 6.5' },
  { value: 'pte', label: 'PTE', maxScore: 90, step: 1, placeholder: 'e.g., 58' },
  { value: 'toefl', label: 'TOEFL', maxScore: 120, step: 1, placeholder: 'e.g., 80' },
  { value: 'moi', label: 'MOI', maxScore: 100, step: 1, placeholder: 'e.g., 70' },
  { value: 'duolingo', label: 'Duolingo', maxScore: 160, step: 5, placeholder: 'e.g., 105' },
  { value: 'none', label: 'No English Test', maxScore: 0, step: 0, placeholder: '' }
];

// Helper function to safely parse JSON
const safeParse = (str) => {
  try {
    return typeof str === 'object' ? str : JSON.parse(str || '[]');
  } catch {
    return [];
  }
};

export default function UniversityList() {
  const [universities, setUniversities] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isUploading, setIsUploading] = useState(false);
  const [isGeneratingAIEdit, setIsGeneratingAIEdit] = useState(false);
  const [uploadedImages, setUploadedImages] = useState({
    logo: null,
    feature_image: null,
    featured_images: [],
  });
  
  // AI Generated Content State for Edit Modal
  const [aiGeneratedContent, setAiGeneratedContent] = useState('');
  
  // Reviews
  const [reviews, setReviews] = useState([
    {
      rating: 0,
      reviewDate: '',
      authorName: '',
      publisherName: '',
      reviewerName: '',
      reviewDescription: '',
    }
  ]);

  // English Tests - Simplified structure
  const [englishTestRequirements, setEnglishTestRequirements] = useState([
    {
      testType: '',
      minScore: '',
    }
  ]);

  // Keywords state for edit form
  const [editKeywords, setEditKeywords] = useState([]);
  const [currentEditKeyword, setCurrentEditKeyword] = useState('');

  // FAQs state for edit form
  const [editFaqs, setEditFaqs] = useState([
    {
      question: '',
      answer: '',
    }
  ]);

  const [showEditModal, setShowEditModal] = useState(false);
  const [editingUniversity, setEditingUniversity] = useState(null);
  const [activeEditTab, setActiveEditTab] = useState('GENERAL');
  const [editForm, setEditForm] = useState({
    name: '',
    university_type: '',
    founded_in: '',
    country: '',
    city: '',
    address: '',
    postcode: '',
    phone_no: '',
    total_students: '',
    international_student: '',
    scholarship: '',
    cgpa: '',
    overview: '',
    academic_programs: '',
    scholarships_financial_support: '',
    campus_life_student_experience: '',
    why_choose: '',
    short_description: '',
    keywords: '[]',
    languages: '',
    accommodation: '',
    intake: '',
    ranking: '',
    alternate_email: '',
    website: '',
    popular: '',
    country_popular: '',
    average_course_fee: '',
    application_fee: '',
    acceptance_rate: '',
    meta_title: '',
    meta_description: '',
    faqs: '[]',
    review_detail: '[]',
    english_test_requirements: '[]',
    logo_url: '',
    feature_image_url: '',
    featured_images: '[]',
    show_in_menu: true, // NEW: Menu visibility field
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 15;
  
  // Search and filter states
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCountry, setFilterCountry] = useState('');
  const [filterPopular, setFilterPopular] = useState('');
  const [filterYear, setFilterYear] = useState('');
  const [filterActive, setFilterActive] = useState('');
  const [filterShowInMenu, setFilterShowInMenu] = useState(''); // NEW: Filter for menu visibility
  const [sortOrder, setSortOrder] = useState('asc');
  
  // Filter visibility state
  const [showFilters, setShowFilters] = useState(false);
  
  // Applied filters state (only applied when search button is clicked)
  const [appliedFilters, setAppliedFilters] = useState({
    search: '',
    country: '',
    popular: '',
    year: '',
    active: '',
    showInMenu: '', // NEW
    sortOrder: 'asc'
  });
  
  // Pagination states
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  
  // Available countries state - will be populated from API
  const [availableCountries, setAvailableCountries] = useState([]);

  useEffect(() => {
    const fetchCountries = async () => {
      const res = await fetch('/api/internal/country', { method: 'POST' });

      if(!res.ok){
        console.log("Error Fetching Countries");
      }

      const data = await res.json();

      setAvailableCountries(data.data);
    }

    fetchCountries()
  }, [])

  // Fetch universities with pagination and filters
  const fetchUniversities = async (page = 1, filters = appliedFilters) => {
    try {
      setIsLoading(true);
      
      // Build query parameters
      const params = new URLSearchParams({
        page: page.toString(),
        limit: itemsPerPage.toString(),
        sortOrder: filters.sortOrder || 'asc'
      });

      // Add filters to query if they exist
      if (filters.search) params.append('search', filters.search);
      if (filters.country) params.append('country', filters.country);
      if (filters.popular !== '') {
        params.append('popular', filters.popular === 'true' ? '1' : '0');
      }
      if (filters.year) params.append('year', filters.year);
      if (filters.active !== '') {
        params.append('active', filters.active === 'true' ? '1' : '0');
      }
      // NEW: Add showInMenu filter
      if (filters.showInMenu !== '') {
        params.append('showInMenu', filters.showInMenu === 'true' ? '1' : '0');
      }

      console.log('Fetching universities with params:', params.toString());

      const response = await fetch(`/api/internal/university?${params}`);
      if (!response.ok) throw new Error('Failed to fetch universities');
      
      const data = await response.json();
      
      if (data.success) {
        console.log('Fetched universities:', data.data?.length || 0, 'Total in database:', data.pagination?.totalItems || 0);
        console.log('Pagination data:', data.pagination);
        
        setUniversities(data.data || []);
        setTotalItems(data.pagination?.totalItems || 0);
        setTotalPages(data.pagination?.totalPages || 1);
        setCurrentPage(data.pagination?.currentPage || page);
        
      } else {
        setUniversities(data.data || data || []);
        setTotalItems(data.data?.length || data?.length || 0);
        setTotalPages(Math.ceil((data.data?.length || data?.length || 0) / itemsPerPage));
      
      }
    } catch (error) {
      console.error('Error fetching universities:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load universities',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Initial load - fetch first page and get available countries
  useEffect(() => {
    fetchUniversities(1, appliedFilters);
  }, [appliedFilters]);

  // Fetch data when page changes
  useEffect(() => {
    fetchUniversities(currentPage, appliedFilters);
  }, [currentPage]);

  // Function to apply filters when search button is clicked
  const applyFilters = () => {
    const newFilters = {
      search: searchTerm,
      country: filterCountry,
      popular: filterPopular,
      year: filterYear,
      active: filterActive,
      showInMenu: filterShowInMenu, // NEW
      sortOrder: sortOrder
    };
    setAppliedFilters(newFilters);
    setCurrentPage(1);
  };

  // Function to clear all filters
  const clearFilters = () => {
    setSearchTerm('');
    setFilterCountry('');
    setFilterPopular('');
    setFilterYear('');
    setFilterActive('');
    setFilterShowInMenu(''); // NEW
    setSortOrder('asc');
    const clearedFilters = {
      search: '',
      country: '',
      popular: '',
      year: '',
      active: '',
      showInMenu: '', // NEW
      sortOrder: 'asc'
    };
    setAppliedFilters(clearedFilters);
    setCurrentPage(1);
  };

  // Handle page change
  const handlePageChange = (newPage) => {
    setCurrentPage(newPage);
  };

  // NEW: Handle menu toggle
  const handleToggleMenuVisibility = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/university/${id}/menu-toggle`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ show_in_menu: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update menu visibility');
      }

      const result = await response.json();
      
      // Update the university in the local state
      setUniversities(universities.map(uni => 
        uni.id === id ? {
          ...uni,
          show_in_menu: result.data.show_in_menu
        } : uni
      ));
      
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: result.message || `Menu visibility ${!currentStatus ? 'enabled' : 'disabled'} successfully`,
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating menu visibility:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update menu visibility',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  // AI Generation function for edit form with streaming support
  const generateAboutWithAIEdit = async () => {
    if (!editForm.name.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'University Name Required',
        text: 'Please enter university name first to generate AI content',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    setIsGeneratingAIEdit(true);
    setAiGeneratedContent('');

    try {
      const response = await fetch('/api/internal/generate-university-description', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          universityName: editForm.name,
          universityType: editForm.university_type,
          country: editForm.country,
          city: editForm.city,
          keywords: editKeywords
        }),
      });

      if (!response.ok) {
        throw new Error(`Failed to generate content: ${response.status} ${response.statusText}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullContent = '';

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          setAiGeneratedContent(fullContent);
          
          Swal.fire({
            icon: 'success',
            title: 'Content Generated!',
            html: `
              <div style="text-align: center;">
                <p>AI content has been generated successfully!</p>
                <p class="text-sm text-gray-600 mt-2">
                  <strong>Word Count:</strong> ${fullContent.split(' ').length} words<br>
                  <strong>Characters:</strong> ${fullContent.length}
                </p>
                <div class="mt-4 p-3 bg-blue-50 rounded-lg">
                  <p class="text-sm text-blue-800">
                    <strong>Instructions:</strong> Copy the content below and paste it into any of the Summernote editors.
                  </p>
                </div>
              </div>
            `,
            confirmButtonColor: '#0B6D76',
            showConfirmButton: true,
            confirmButtonText: 'Got it!'
          });
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            
            if (data === '[DONE]') {
              continue;
            }

            if (data.trim() === '') {
              continue;
            }

            try {
              const parsed = JSON.parse(data);
              
              if (parsed.type === 'content') {
                fullContent += parsed.content;
                setAiGeneratedContent(fullContent);
              }
            } catch (e) {
              if (data && data.trim()) {
                fullContent += data;
                setAiGeneratedContent(fullContent);
              }
            }
          }
        }
      }

    } catch (error) {
      console.error('Error generating AI content:', error);
      
      Swal.fire({
        icon: 'error',
        title: 'AI Generation Failed',
        text: error.message || 'Failed to generate content. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsGeneratingAIEdit(false);
    }
  };

  // Function to copy AI content to clipboard (Edit Modal)
  const copyAIContentToClipboardEdit = () => {
    if (!aiGeneratedContent) {
      Swal.fire({
        icon: 'warning',
        title: 'No Content',
        text: 'Please generate AI content first',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    navigator.clipboard.writeText(aiGeneratedContent)
      .then(() => {
        Swal.fire({
          icon: 'success',
          title: 'Copied!',
          text: 'AI content copied to clipboard. You can now paste it into any editor.',
          confirmButtonColor: '#0B6D76'
        });
      })
      .catch(err => {
        console.error('Failed to copy:', err);
        Swal.fire({
          icon: 'error',
          title: 'Copy Failed',
          text: 'Could not copy content. Please select and copy manually.',
          confirmButtonColor: '#0B6D76'
        });
      });
  };

  // Keywords handlers for edit form
  const handleAddEditKeyword = () => {
    if (currentEditKeyword.trim() && !editKeywords.includes(currentEditKeyword.trim())) {
      const newKeywords = [...editKeywords, currentEditKeyword.trim()];
      setEditKeywords(newKeywords);
      setEditForm(prev => ({
        ...prev,
        keywords: JSON.stringify(newKeywords),
      }));
      setCurrentEditKeyword('');
    }
  };

  const handleRemoveEditKeyword = (index) => {
    const newKeywords = [...editKeywords];
    newKeywords.splice(index, 1);
    setEditKeywords(newKeywords);
    setEditForm(prev => ({
      ...prev,
      keywords: JSON.stringify(newKeywords),
    }));
  };

  // FAQs handlers for edit form
  const handleFaqChange = (index, field, value) => {
    const updatedFaqs = [...editFaqs];
    updatedFaqs[index][field] = value;
    setEditFaqs(updatedFaqs);
    setEditForm(prev => ({
      ...prev,
      faqs: JSON.stringify(updatedFaqs),
    }));
  };

  const addFaq = () => {
    setEditFaqs([
      ...editFaqs,
      {
        question: '',
        answer: '',
      }
    ]);
  };

  const removeFaq = (index) => {
    if (editFaqs.length > 1) {
      const updatedFaqs = [...editFaqs];
      updatedFaqs.splice(index, 1);
      setEditFaqs(updatedFaqs);
      setEditForm(prev => ({
        ...prev,
        faqs: JSON.stringify(updatedFaqs),
      }));
    }
  };

  const handleEditClick = (university) => {
    const safeJsonField = (field) => {
      if (!field) return '[]';
      if (typeof field === 'string') return field;
      if (typeof field === 'object') return JSON.stringify(field);
      return '[]';
    };

    const parsedReviews = (() => {
      try {
        const r = typeof university.review_detail === 'string' ? JSON.parse(university.review_detail) : (university.review_detail || []);
        return Array.isArray(r) && r.length > 0 ? r : [{ rating: '', reviewDate: '', authorName: '', publisherName: '', reviewerName: '', reviewDescription: '' }];
      } catch {
        return [{ rating: '', reviewDate: '', authorName: '', publisherName: '', reviewerName: '', reviewDescription: '' }];
      }
    })();

    const parsedEnglishTests = (() => {
      try {
        const tests = typeof university.english_test_requirements === 'string' 
          ? JSON.parse(university.english_test_requirements) 
          : (university.english_test_requirements || []);
        return Array.isArray(tests) && tests.length > 0 ? tests : [{ testType: '', minScore: '' }];
      } catch {
        return [{ testType: '', minScore: '' }];
      }
    })();

    // Parse keywords
    const parsedKeywords = (() => {
      try {
        return typeof university.keywords === 'string' 
          ? JSON.parse(university.keywords || '[]') 
          : (university.keywords || []);
      } catch {
        return [];
      }
    })();

    // Parse featured images
    const parsedFeaturedImages = (() => {
      try {
        return typeof university.featured_images === 'string' 
          ? JSON.parse(university.featured_images || '[]') 
          : (university.featured_images || []);
      } catch {
        return [];
      }
    })();

    // Parse FAQs
    const parsedFaqs = (() => {
      try {
        const faqsFromJson = typeof university.faqs === 'string' 
          ? JSON.parse(university.faqs || '[]') 
          : (university.faqs || []);
        
        if (Array.isArray(faqsFromJson) && faqsFromJson.length > 0) {
          return faqsFromJson;
        }
        
        if (university.faqs && Array.isArray(university.faqs) && university.faqs.length > 0) {
          return university.faqs;
        }
        
        return [{ question: '', answer: '' }];
      } catch {
        return [{ question: '', answer: '' }];
      }
    })();

    setEditingUniversity(university);
    setReviews(parsedReviews);
    setEnglishTestRequirements(parsedEnglishTests);
    setEditKeywords(parsedKeywords);
    setEditFaqs(parsedFaqs);
    setAiGeneratedContent('');

    const scholarshipValue = university.scholarship === 1 ? '1' : '0';
    const popularValue = university.popular === 1 ? '1' : '0';
    const countryPopularValue = university.country_popular === 1 ? '1' : '0';
    const showInMenuValue = university.show_in_menu !== undefined ? university.show_in_menu : true; // NEW

    setEditForm({
      name: university.name || '',
      university_type: university.university_type || '',
      founded_in: university.founded_in || '',
      country: university.country || '',
      city: university.city || '',
      address: university.address || '',
      postcode: university.postcode || '',
      phone_no: university.phone_no || '',
      total_students: university.total_students || '',
      international_student: university.international_student || '',
      scholarship: scholarshipValue,
      cgpa: university.cgpa || '',
      overview: university.overview || '',
      academic_programs: university.academic_programs || '',
      scholarships_financial_support: university.scholarships_financial_support || '',
      campus_life_student_experience: university.campus_life_student_experience || '',
      why_choose: university.why_choose || '',
      short_description: university.short_description || '',
      keywords: JSON.stringify(parsedKeywords),
      languages: university.languages || '',
      accommodation: university.accommodation || '',
      intake: university.intake || '',
      ranking: university.ranking || '',
      alternate_email: university.alternate_email || '',
      website: university.website || '',
      popular: popularValue,
      country_popular: countryPopularValue,
      average_course_fee: university.average_course_fee || '',
      application_fee: university.application_fee || '',
      acceptance_rate: university.acceptance_rate || '',
      meta_title: university.meta_title || '',
      meta_description: university.meta_description || '',
      faqs: JSON.stringify(parsedFaqs),
      review_detail: JSON.stringify(parsedReviews),
      english_test_requirements: JSON.stringify(parsedEnglishTests),
      logo_url: university.logo || '',
      feature_image_url: university.feature_image || '',
      featured_images: JSON.stringify(parsedFeaturedImages),
      show_in_menu: showInMenuValue, // NEW
    });
    setActiveEditTab('GENERAL');
    setShowEditModal(true);
    setUploadedImages({
      logo: null,
      feature_image: null,
      featured_images: [],
    });
  };

  const handleDelete = async (id) => {
    const confirmDelete = await Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#dc3545',
      cancelButtonColor: '#6c757d',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel',
    });

    if (confirmDelete.isConfirmed) {
      try {
        const response = await fetch(`/api/internal/university/${id}`, { method: 'DELETE' });
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || errorData.message || 'Failed to delete university');
        }

        setUniversities(universities.filter(uni => uni.id !== id));
        Swal.fire({
          icon: 'success',
          title: 'Deleted!',
          text: 'University has been deleted.',
          confirmButtonColor: '#0B6D76'
        });
      } catch (error) {
        console.error('Error deleting university:', error);
        Swal.fire({
          icon: 'error',
          title: 'Error!',
          text: 'Failed to delete university',
          confirmButtonColor: '#0B6D76'
        });
      }
    }
  };

  const handleTogglePopular = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/university/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ popular: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update university');
      }

      const updatedUniversity = await response.json();
      setUniversities(universities.map(uni => uni.id === id ? updatedUniversity : uni));
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: 'University status updated successfully',
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating university:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update university status',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleToggleCountryPopular = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/university/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ country_popular: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update university');
      }

      const updatedUniversity = await response.json();
      setUniversities(universities.map(uni => uni.id === id ? updatedUniversity : uni));
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: 'University country popular status updated successfully',
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating university country popular:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update university country popular status',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  // Handle active/inactive toggle
  const handleToggleActive = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/university/${id}/active`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update university active status');
      }

      const result = await response.json();
      
      setUniversities(universities.map(uni => 
        uni.id === id ? {
          ...uni,
          is_active: result.data.is_active
        } : uni
      ));
      
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: result.message || `University ${!currentStatus ? 'activated' : 'deactivated'} successfully`,
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating university active status:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update university active status',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const uploadImage = async (file, uploadType = 'university-logo') => {
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', uploadType);

      const response = await fetch('/api/internal/upload', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Failed to upload image');
      }

      const data = await response.json();
      return data.s3Key;
    } catch (error) {
      console.error('Error uploading image:', error);
      throw error;
    }
  };

  // Handle multiple featured images upload
  const handleMultipleImageUpload = async (e) => {
    const files = Array.from(e.target.files);
    if (!files.length) return;

    try {
      setIsUploading(true);

      const uploadedUrls = [];
      for (const file of files) {
        const imageUrl = await uploadImage(file, 'university-featured');
        uploadedUrls.push(imageUrl);
      }

      const newFeaturedImages = files.map((file, index) => ({
        file,
        url: uploadedUrls[index]
      }));

      setUploadedImages(prev => ({
        ...prev,
        featured_images: [...prev.featured_images, ...newFeaturedImages]
      }));

      const currentImages = JSON.parse(editForm.featured_images || '[]');
      const updatedImages = [...currentImages, ...uploadedUrls];
      
      setEditForm(prev => ({
        ...prev,
        featured_images: JSON.stringify(updatedImages),
      }));

    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Error',
        text: error.message || 'Failed to upload images',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileUpload = async (e, field) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      setIsUploading(true);

      let uploadType = 'university-logo';
      if (field === 'logo') uploadType = 'university-logo';
      else if (field === 'feature_image') uploadType = 'university-feature';
      
      const imageUrl = await uploadImage(file, uploadType);
    
      setUploadedImages(prev => ({
        ...prev,
        [field]: { file, url: imageUrl }
      }));
      setEditForm(prev => ({
        ...prev,
        [`${field}_url`]: imageUrl,
        [field]: imageUrl
      }));

    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Error',
        text: error.message || 'Failed to upload image',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsUploading(false);
    }
  };

  // Remove featured image
  const removeFeaturedImage = (index) => {
    const updatedImages = [...uploadedImages.featured_images];
    updatedImages.splice(index, 1);
    
    setUploadedImages(prev => ({
      ...prev,
      featured_images: updatedImages
    }));
    
    const currentImages = JSON.parse(editForm.featured_images || '[]');
    currentImages.splice(index, 1);
    
    setEditForm(prev => ({
      ...prev,
      featured_images: JSON.stringify(currentImages),
    }));
  };

  const removeImage = (index, field) => {
    setUploadedImages(prev => ({
      ...prev,
      [field]: null
    }));
    setEditForm(prev => ({
      ...prev,
      [`${field}_url`]: ''
    }));
  };

  // Review Handlers
  const handleReviewChange = (index, field, value) => {
    const updatedReviews = [...reviews];
    updatedReviews[index][field] = value;
    setReviews(updatedReviews);
    setEditForm(prev => ({
      ...prev,
      review_detail: JSON.stringify(updatedReviews),
    }));
  };

  const addReview = () => {
    setReviews([
      ...reviews,
      {
        rating: 0,
        reviewDate: '',
        authorName: '',
        publisherName: '',
        reviewerName: '',
        reviewDescription: '',
      }
    ]);
  };

  const removeReview = (index) => {
    if (reviews.length > 1) {
      const updatedReviews = [...reviews];
      updatedReviews.splice(index, 1);
      setReviews(updatedReviews);
      setEditForm(prev => ({
        ...prev,
        review_detail: JSON.stringify(updatedReviews),
      }));
    }
  };

  // English Test Handlers - Simplified
  const handleEnglishTestChange = (index, field, value) => {
    const updatedTests = [...englishTestRequirements];
    updatedTests[index][field] = value;
    setEnglishTestRequirements(updatedTests);
    setEditForm(prev => ({
      ...prev,
      english_test_requirements: JSON.stringify(updatedTests),
    }));
  };

  const addEnglishTest = () => {
    setEnglishTestRequirements([
      ...englishTestRequirements,
      {
        testType: '',
        minScore: '',
      }
    ]);
  };

  const removeEnglishTest = (index) => {
    if (englishTestRequirements.length > 1) {
      const updatedTests = [...englishTestRequirements];
      updatedTests.splice(index, 1);
      setEnglishTestRequirements(updatedTests);
      setEditForm(prev => ({
        ...prev,
        english_test_requirements: JSON.stringify(updatedTests),
      }));
    }
  };

  const getCurrentEnglishTest = (testType) => {
    return englishTests.find(test => test.value === testType);
  };

  const handleEditChange = (e) => {
    const { name, value, type, checked } = e.target;
    setEditForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (checked ? '1' : '0') : value
    }));
  };

  const handleEditEditorChange = (name, content) => {
    setEditForm(prev => ({
      ...prev,
      [name]: content || '',
    }));
  };

  const handleEditSubmit = async (e) => {
    e.preventDefault();
    
    if (!editForm.name.trim()) {
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: 'University name is required',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    if (!editForm.university_type.trim()) {
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: 'University type is required',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const updateData = {
        name: editForm.name.trim(),
        university_type: editForm.university_type.trim(),
        founded_in: editForm.founded_in.trim() || null,
        country: editForm.country.trim() || null,
        city: editForm.city.trim() || null,
        address: editForm.address.trim() || null,
        postcode: editForm.postcode.trim() || null,
        phone_no: editForm.phone_no || null,
        total_students: editForm.total_students || null,
        international_student: editForm.international_student || null,
        scholarship: editForm.scholarship,
        cgpa: editForm.cgpa || null,
        overview: editForm.overview.trim() || null,
        academic_programs: editForm.academic_programs.trim() || null,
        scholarships_financial_support: editForm.scholarships_financial_support.trim() || null,
        campus_life_student_experience: editForm.campus_life_student_experience.trim() || null,
        why_choose: editForm.why_choose.trim() || null,
        short_description: editForm.short_description.trim() || null,
        keywords: editForm.keywords,
        languages: editForm.languages.trim() || null,
        accommodation: editForm.accommodation.trim() || null,
        intake: editForm.intake.trim() || null,
        ranking: editForm.ranking,
        alternate_email: editForm.alternate_email.trim() || null,
        website: editForm.website.trim() || null,
        popular: editForm.popular,
        country_popular: editForm.country_popular,
        average_course_fee: editForm.average_course_fee.trim() || null,
        application_fee: editForm.application_fee ? parseFloat(editForm.application_fee) : null,
        acceptance_rate: editForm.acceptance_rate.trim() || null,
        meta_title: editForm.meta_title.trim() || null,
        meta_description: editForm.meta_description.trim() || null,
        faqs: editForm.faqs,
        review_detail: editForm.review_detail,
        english_test_requirements: editForm.english_test_requirements,
        logo_url: editForm.logo_url || null,
        feature_image_url: editForm.feature_image_url || null,
        featured_images: editForm.featured_images,
        show_in_menu: editForm.show_in_menu, // NEW
      };
      
      const response = await fetch(`/api/internal/university/${editingUniversity.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updateData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.log('Update error response:', errorData);
        throw new Error(errorData.error || errorData.message || 'Failed to update university');
      }

      const data = await response.json();
      
      setUniversities(universities.map(uni => 
        uni.id === editingUniversity.id ? {
          ...uni,
          name: data.data.name,
          university_type: data.data.university_type,
          founded_in: data.data.founded_in,
          country: data.data.country,
          city: data.data.city,
          address: data.data.address,
          postcode: data.data.postcode,
          phone_no: data.data.phone_no,
          total_students: parseInt(data.data.total_students) || 0,
          international_student: parseInt(data.data.international_student) || 0,
          scholarship: data.data.scholarship,
          cgpa: data.data.cgpa,
          overview: data.data.overview || '',
          academic_programs: data.data.academic_programs || '',
          scholarships_financial_support: data.data.scholarships_financial_support || '',
          campus_life_student_experience: data.data.campus_life_student_experience || '',
          why_choose: data.data.why_choose || '',
          short_description: data.data.short_description || '',
          keywords: data.data.keywords || '[]',
          languages: data.data.languages,
          accommodation: data.data.accommodation,
          intake: data.data.intake,
          ranking: data.data.ranking,
          alternate_email: data.data.alternate_email,
          website: data.data.website,
          popular: data.data.popular,
          country_popular: data.data.country_popular,
          average_course_fee: data.data.average_course_fee,
          application_fee: data.data.application_fee,
          acceptance_rate: data.data.acceptance_rate || '',
          meta_title: data.data.meta_title || '',
          meta_description: data.data.meta_description || '',
          faqs: data.data.faqs || '[]',
          review_detail: data.data.review_detail,
          english_test_requirements: data.data.english_test_requirements,
          logo_url: data.data.logo_url,
          feature_image_url: data.data.feature_image_url,
          featured_images: data.data.featured_images || '[]',
          show_in_menu: data.data.show_in_menu, // NEW
        } : uni
      ));

      setShowEditModal(false);
      setEditingUniversity(null);
      setActiveEditTab('GENERAL');
      setEditForm({
        name: '',
        university_type: '',
        founded_in: '',
        country: '',
        city: '',
        address: '',
        postcode: '',
        phone_no: '',
        total_students: '',
        international_student: '',
        scholarship: '',
        cgpa: '',
        overview: '',
        academic_programs: '',
        scholarships_financial_support: '',
        campus_life_student_experience: '',
        why_choose: '',
        short_description: '',
        keywords: '[]',
        languages: '',
        accommodation: '',
        intake: '',
        ranking: '',
        alternate_email: '',
        website: '',
        popular: '',
        country_popular: '',
        average_course_fee: '',
        application_fee: '',
        acceptance_rate: '',
        meta_title: '',
        meta_description: '',
        faqs: '[]',
        review_detail: '[]',
        english_test_requirements: '[]',
        logo_url: '',
        feature_image_url: '',
        featured_images: '[]',
        show_in_menu: true,
      });
      setEditKeywords([]);
      setCurrentEditKeyword('');
      setEditFaqs([{ question: '', answer: '' }]);
      setAiGeneratedContent('');

      setUploadedImages({
        logo: null,
        feature_image: null,
        featured_images: []
      });
      
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: 'University updated successfully',
        confirmButtonColor: '#0B6D76'
      });
    } catch (error) {
      console.error('Error updating university:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update university',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Tab Content Renderer for Edit Modal
  const renderEditContent = () => {
    switch (activeEditTab) {
      case 'GENERAL':
        return (
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  University Name *
                </label>
                <input
                  type="text"
                  name="name"
                  value={editForm.name}
                  onChange={handleEditChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  University Type *
                </label>
                <select
                  name="university_type"
                  value={editForm.university_type}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                >
                  <option value="">Select university type</option>
                  {universityTypes.map((type) => (
                    <option key={type.value} value={type.value}>
                      {type.label}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Founded In
                </label>
                <input
                  type="text"
                  name="founded_in"
                  value={editForm.founded_in}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., 1990"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Country
                </label>
                <input
                  type="text"
                  name="country"
                  value={editForm.country}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  City
                </label>
                <input
                  type="text"
                  name="city"
                  value={editForm.city}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Minimum CGPA Required
                </label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  max="4"
                  name="cgpa"
                  value={editForm.cgpa}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., 3.0"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Popular Status
                </label>
                <select
                  name="popular"
                  value={editForm.popular}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">Select Popular Status</option>
                  <option value="1">Yes</option>
                  <option value="0">No</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Country Popular Status
                </label>
                <select
                  name="country_popular"
                  value={editForm.country_popular}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">Select Country Popular Status</option>
                  <option value="1">Yes</option>
                  <option value="0">No</option>
                </select>
              </div>

              {/* NEW: Menu Visibility Field */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Show in Menu
                </label>
                <select
                  name="show_in_menu"
                  value={editForm.show_in_menu ? '1' : '0'}
                  onChange={(e) => setEditForm(prev => ({
                    ...prev,
                    show_in_menu: e.target.value === '1'
                  }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="1">Yes</option>
                  <option value="0">No</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">Show this university in navigation menu</p>
              </div>
            </div>
            
            {/* Reviews Section */}
            <div className="space-y-4 md:col-span-2">
              <div className="flex justify-between items-center">
                <h3 className="text-lg font-medium">University Reviews</h3>
                <button
                  type="button"
                  onClick={addReview}
                  className="bg-blue-500 text-white px-3 py-1 rounded text-sm"
                >
                  Add Review
                </button>
              </div>

              {reviews.map((review, index) => (
                <div key={index} className="p-4 border rounded-lg space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Rating</label>
                      <select
                        value={review.rating}
                        onChange={(e) => handleReviewChange(index, 'rating', e.target.value)}
                        className="w-full border px-3 py-2 rounded"
                      >
                        <option value="0">Select rating</option>
                        <option value="1">1 Star</option>
                        <option value="2">2 Stars</option>
                        <option value="3">3 Stars</option>
                        <option value="4">4 Stars</option>
                        <option value="5">5 Stars</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
                      <input
                        type="date"
                        value={review.reviewDate}
                        onChange={(e) => handleReviewChange(index, 'reviewDate', e.target.value)}
                        className="w-full border px-3 py-2 rounded"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Author's Name</label>
                      <input
                        type="text"
                        value={review.authorName}
                        onChange={(e) => handleReviewChange(index, 'authorName', e.target.value)}
                        className="w-full border px-3 py-2 rounded"
                        placeholder="Author's name"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Publisher's Name</label>
                      <input
                        type="text"
                        value={review.publisherName}
                        onChange={(e) => handleReviewChange(index, 'publisherName', e.target.value)}
                        className="w-full border px-3 py-2 rounded"
                        placeholder="Publisher's name"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Reviewer's Name</label>
                      <input
                        type="text"
                        value={review.reviewerName}
                        onChange={(e) => handleReviewChange(index, 'reviewerName', e.target.value)}
                        className="w-full border px-3 py-2 rounded"
                        placeholder="Reviewer's name"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Review Description</label>
                    <textarea
                      value={review.reviewDescription}
                      onChange={(e) => handleReviewChange(index, 'reviewDescription', e.target.value)}
                      className="w-full border px-3 py-2 rounded"
                      rows={3}
                      placeholder="Review description"
                    />
                  </div>
                  {reviews.length > 1 && (
                    <div className="flex justify-end">
                      <button
                        type="button"
                        onClick={() => removeReview(index)}
                        className="bg-red-500 text-white px-3 py-1 rounded text-sm"
                      >
                        Remove Review
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        );

      case 'MORE DETAIL':
        return (
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Address */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Address
                </label>
                <input
                  type="text"
                  name="address"
                  value={editForm.address}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              {/* Postcode */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Postcode
                </label>
                <input
                  type="text"
                  name="postcode"
                  value={editForm.postcode}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              {/* Phone Number */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Phone Number
                </label>
                <input
                  type="text"
                  name="phone_no"
                  value={editForm.phone_no}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., +1 234 567 8900"
                />
              </div>

              {/* Total Students */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Total Students
                </label>
                <input
                  type="number"
                  name="total_students"
                  value={editForm.total_students}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              {/* International Students */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  International Students
                </label>
                <input
                  type="number"
                  name="international_student"
                  value={editForm.international_student}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              {/* Scholarship */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Scholarship
                </label>
                <select
                  name="scholarship"
                  value={editForm.scholarship}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">Select Scholarship Availability</option>
                  <option value="1">Yes</option>
                  <option value="0">No</option>
                </select>
              </div>

              {/* Teaching Languages */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Teaching Languages
                </label>
                <input
                  type="text"
                  name="languages"
                  value={editForm.languages}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., English, Spanish"
                />
              </div>

              {/* Intake Periods */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Intake Periods
                </label>
                <input
                  type="text"
                  name="intake"
                  value={editForm.intake}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., January, September"
                />
              </div>

              {/* Ranking */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Ranking
                </label>
                <input
                  type="text"
                  name="ranking"
                  value={editForm.ranking}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., Top 100 worldwide"
                />
              </div>

              {/* Alternate Email */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Alternate Email
                </label>
                <input
                  type="email"
                  name="alternate_email"
                  value={editForm.alternate_email}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>

              {/* Website */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Website
                </label>
                <input
                  type="url"
                  name="website"
                  value={editForm.website}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="https://example.com"
                />
              </div>

              {/* NEW FIELDS */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Average Course Fee
                </label>
                <input
                  type="text"
                  name="average_course_fee"
                  value={editForm.average_course_fee}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., 100-200, 500-1000"
                />
                <p className="text-xs text-gray-500 mt-1">Enter fee range (e.g., 100-200 USD)</p>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Application Fee
                </label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  name="application_fee"
                  value={editForm.application_fee}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., 50, 100, 150"
                />
                <p className="text-xs text-gray-500 mt-1">Enter application fee amount</p>
              </div>

              {/* NEW ACCEPTANCE RATE FIELD */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Acceptance Rate
                </label>
                <input
                  type="text"
                  name="acceptance_rate"
                  value={editForm.acceptance_rate}
                  onChange={handleEditChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="e.g., 25%, 40-50%, 60%"
                />
                <p className="text-xs text-gray-500 mt-1">Enter acceptance rate (e.g., 25%, 40-50%)</p>
              </div>
            </div>

            {/* Accommodation Fields */}
            <div className="md:col-span-2 border-t pt-4 mt-4">
              <h3 className="text-lg font-medium mb-4">Accommodation Information</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Accommodation Type</label>
                  <input
                    name="accommodation"
                    value={editForm.accommodation}
                    onChange={handleEditChange}
                    className="w-full px-4 py-2 border rounded-lg"
                    placeholder="e.g., On-campus dormitory, Off-campus apartments"
                  />
                  <p className="text-xs text-gray-500 mt-1">Types of accommodation available</p>
                </div>
              </div>
            </div>
          </div>
        );

      case 'ENGLISH TESTS':
        return (
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h3 className="text-lg font-medium">English Test Requirements</h3>
              <button
                type="button"
                onClick={addEnglishTest}
                className="bg-green-500 text-white px-3 py-1 rounded text-sm"
              >
                Add English Test
              </button>
            </div>

            <p className="text-sm text-gray-600">
              Add the minimum English language test scores required for admission.
            </p>

            {englishTestRequirements.map((test, index) => (
              <div key={index} className="p-4 border rounded-lg space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Test Type*</label>
                    <select
                      value={test.testType}
                      onChange={(e) => handleEnglishTestChange(index, 'testType', e.target.value)}
                      className="w-full border px-3 py-2 rounded"
                      required
                    >
                      <option value="">Select test type</option>
                      {englishTests.map(testOption => (
                        <option key={testOption.value} value={testOption.value}>
                          {testOption.label}
                        </option>
                      ))}
                    </select>
                  </div>

                  {test.testType && test.testType !== 'none' && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Minimum Score Required*
                      </label>
                      <input
                        type="number"
                        step={getCurrentEnglishTest(test.testType)?.step || 0.5}
                        min="0"
                        max={getCurrentEnglishTest(test.testType)?.maxScore || 9}
                        value={test.minScore}
                        onChange={(e) => handleEnglishTestChange(index, 'minScore', e.target.value)}
                        placeholder={getCurrentEnglishTest(test.testType)?.placeholder || 'Enter minimum score'}
                        className="w-full border px-3 py-2 rounded"
                        required
                      />
                    </div>
                  )}
                </div>

                {englishTestRequirements.length > 1 && (
                  <div className="flex justify-end">
                    <button
                      type="button"
                      onClick={() => removeEnglishTest(index)}
                      className="bg-red-500 text-white px-3 py-1 rounded text-sm"
                    >
                      Remove Test
                    </button>
                  </div>
                )}
              </div>
            ))}

            {englishTestRequirements.length === 0 && (
              <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-lg">
                <p className="text-gray-500">No English test requirements added yet.</p>
                <button
                  type="button"
                  onClick={addEnglishTest}
                  className="mt-2 bg-green-500 text-white px-4 py-2 rounded text-sm"
                >
                  Add First Test Requirement
                </button>
              </div>
            )}
          </div>
        );

      case 'IMAGES':
        const parsedFeaturedImages = JSON.parse(editForm.featured_images || '[]');
        
        return (
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">University Logo</label>
              {editingUniversity.logo && 
                <img
                  src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${editingUniversity.logo}`}
                  alt="Logo preview"
                  className="h-20 object-contain"
                />
              }
              <input
                type="file"
                accept="image/*"
                onChange={(e) => handleFileUpload(e, 'logo')}
                className="block w-full text-sm text-gray-500
                  file:mr-4 file:py-2 file:px-4
                  file:rounded-md file:border-0
                  file:text-sm file:font-semibold
                  file:bg-blue-50 file:text-blue-700
                  hover:file:bg-blue-100"
                disabled={isUploading}
              />
              {uploadedImages.logo && (
                <div className="mt-2">
                  <img
                    src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uploadedImages.logo.url}`}
                    alt="Logo preview"
                    className="h-20 object-contain"
                  />
                  <p className="text-xs text-gray-500 mt-1">{uploadedImages.logo.file.name}</p>
                  <button
                    type="button"
                    onClick={() => removeImage(0, 'logo')}
                    className="mt-1 text-red-600 text-sm"
                    disabled={isUploading}
                  >
                    Remove
                  </button>
                </div>
              )}
              {isUploading && !uploadedImages.logo && (
                <div className="mt-2 text-sm text-gray-500">Uploading logo...</div>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Feature Image</label>
              { editingUniversity.feature_image &&
                <img
                  src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${editingUniversity.feature_image}`}
                  alt="Featured Image preview"
                  className="h-20 object-contain"
                />
              }
              <input
                type="file"
                accept="image/*"
                onChange={(e) => handleFileUpload(e, 'feature_image')}
                className="block w-full text-sm text-gray-500
                  file:mr-4 file:py-2 file:px-4
                  file:rounded-md file:border-0
                  file:text-sm file:font-semibold
                  file:bg-blue-50 file:text-blue-700
                  hover:file:bg-blue-100"
                disabled={isUploading}
              />
              {uploadedImages.feature_image && (
                <div className="mt-2">
                  <img
                    src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uploadedImages.feature_image.url}`}
                    alt="Feature image preview"
                    className="h-40 object-contain"
                  />
                  <p className="text-xs text-gray-500 mt-1">{uploadedImages.feature_image.file.name}</p>
                  <button
                    type="button"
                    onClick={() => removeImage(0, 'feature_image')}
                    className="mt-1 text-red-600 text-sm"
                    disabled={isUploading}
                  >
                    Remove
                  </button>
                </div>
              )}
              {isUploading && !uploadedImages.feature_image && (
                <div className="mt-2 text-sm text-gray-500">Uploading feature image...</div>
              )}
            </div>

            {/* Multiple Featured Images Section */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Featured Images</label>
              <p className="text-sm text-gray-600 mb-2">Upload multiple images to showcase the university</p>
              
              {/* Display existing featured images */}
              {parsedFeaturedImages.length > 0 && (
                <div className="mb-4">
                  <p className="text-sm font-medium text-gray-700 mb-2">Current Featured Images:</p>
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    {parsedFeaturedImages.map((imageUrl, index) => (
                      <div key={index} className="relative border rounded-lg p-2">
                        <img
                          src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imageUrl}`}
                          alt={`Featured ${index + 1}`}
                          className="h-32 w-full object-cover rounded"
                        />
                        <button
                          type="button"
                          onClick={() => {
                            const updatedImages = [...parsedFeaturedImages];
                            updatedImages.splice(index, 1);
                            setEditForm(prev => ({
                              ...prev,
                              featured_images: JSON.stringify(updatedImages),
                            }));
                          }}
                          className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              
              {/* Upload new featured images */}
              <input
                type="file"
                accept="image/*"
                multiple
                onChange={handleMultipleImageUpload}
                className="block w-full text-sm text-gray-500
                  file:mr-4 file:py-2 file:px-4
                  file:rounded-md file:border-0
                  file:text-sm file:font-semibold
                  file:bg-blue-50 file:text-blue-700
                  hover:file:bg-blue-100"
                disabled={isUploading}
              />
              
              {/* Display newly uploaded featured images preview */}
              {uploadedImages.featured_images.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm font-medium text-gray-700 mb-2">New Uploads:</p>
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    {uploadedImages.featured_images.map((image, index) => (
                      <div key={index} className="relative border rounded-lg p-2">
                        <img
                          src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${image.url}`}
                          alt={`New Featured ${index + 1}`}
                          className="h-32 w-full object-cover rounded"
                        />
                        <button
                          type="button"
                          onClick={() => removeFeaturedImage(index)}
                          className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs"
                        >
                          ×
                        </button>
                        <p className="text-xs text-gray-500 mt-1 truncate">{image.file.name}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              
              {isUploading && uploadedImages.featured_images.length === 0 && parsedFeaturedImages.length === 0 && (
                <div className="mt-2 text-sm text-gray-500">Uploading featured images...</div>
              )}
            </div>
          </div>
        );

      case 'ABOUT UNIVERSITY':
        return (
          <div className="space-y-6">
            {/* Short Description Field */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Short Description
              </label>
              <textarea
                name="short_description"
                value={editForm.short_description}
                onChange={handleEditChange}
                className="w-full border px-4 py-2 rounded-lg"
                rows={4}
                placeholder="Enter a brief description of the university (this appears in listings and cards)"
                maxLength={300}
              />
              <p className="text-xs text-gray-500 mt-1">
                {editForm.short_description?.length || 0}/300 characters
              </p>
            </div>

            {/* Keywords Section */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Keywords
              </label>
              <div className="flex gap-2 mb-3">
                <input
                  type="text"
                  value={currentEditKeyword}
                  onChange={(e) => setCurrentEditKeyword(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddEditKeyword())}
                  className="flex-1 border px-4 py-2 rounded-lg"
                  placeholder="Type keyword and press Enter or click Add"
                />
                <button
                  type="button"
                  onClick={handleAddEditKeyword}
                  className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600"
                >
                  Add
                </button>
              </div>
              
              {/* Display added keywords */}
              {editKeywords.length > 0 && (
                <div className="mt-3">
                  <p className="text-sm text-gray-600 mb-2">Added keywords:</p>
                  <div className="flex flex-wrap gap-2">
                    {editKeywords.map((keyword, index) => (
                      <div
                        key={index}
                        className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm flex items-center gap-1"
                      >
                        {keyword}
                        <button
                          type="button"
                          onClick={() => handleRemoveEditKeyword(index)}
                          className="text-blue-600 hover:text-blue-800"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              <p className="text-xs text-gray-500 mt-2">
                Add relevant keywords to help users find this university (e.g., "engineering", "business school", "research university")
              </p>
            </div>

            {/* Overview Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Overview
              </label>
              
              <SummernoteEditor
                value={editForm.overview}
                onChange={(content) => handleEditEditorChange('overview', content)}
              />
            </div>

            {/* Academic Programs Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Academic Programs
              </label>
              
              <SummernoteEditor
                value={editForm.academic_programs}
                onChange={(content) => handleEditEditorChange('academic_programs', content)}
              />
            </div>

            {/* Scholarships and Financial Support Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Scholarships and Financial Support
              </label>
              
              <SummernoteEditor
                value={editForm.scholarships_financial_support}
                onChange={(content) => handleEditEditorChange('scholarships_financial_support', content)}
              />
            </div>

            {/* Campus Life and Student Experience Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Campus Life and Student Experience
              </label>
              
              <SummernoteEditor
                value={editForm.campus_life_student_experience}
                onChange={(content) => handleEditEditorChange('campus_life_student_experience', content)}
              />
            </div>

            {/* Why Choose Editor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Why Choose
              </label>
              
              <SummernoteEditor
                value={editForm.why_choose}
                onChange={(content) => handleEditEditorChange('why_choose', content)}
              />
            </div>

            {/* AI Generated Content Section */}
            <div className="mt-8 border-t pt-6">
              <div className="flex justify-between items-center mb-3">
                <label className="block text-sm font-medium text-gray-700">
                  🤖 AI Generated Content
                </label>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={generateAboutWithAIEdit}
                    disabled={isGeneratingAIEdit}
                    className="bg-purple-500 text-white px-3 py-1 rounded text-sm flex items-center gap-2 hover:bg-purple-600 disabled:opacity-50"
                  >
                    {isGeneratingAIEdit ? (
                      <>
                        <svg className="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Generating...
                      </>
                    ) : (
                      <>
                        <span>🤖</span>
                        Generate with AI
                      </>
                    )}
                  </button>
                  <button
                    type="button"
                    onClick={copyAIContentToClipboardEdit}
                    disabled={!aiGeneratedContent}
                    className="bg-blue-500 text-white px-3 py-1 rounded text-sm hover:bg-blue-600 disabled:opacity-50"
                  >
                    📋 Copy to Clipboard
                  </button>
                </div>
              </div>
              
              {isGeneratingAIEdit ? (
                <div className="p-6 text-center border-2 border-dashed border-gray-300 rounded-lg">
                  <div className="animate-spin h-8 w-8 border-4 border-purple-500 border-t-transparent rounded-full mx-auto mb-3"></div>
                  <p className="text-gray-600">🤖 AI is generating content about {editForm.name}...</p>
                  <p className="text-sm text-gray-500 mt-1">This may take 30-60 seconds. Please wait.</p>
                </div>
              ) : aiGeneratedContent ? (
                <>
                  <div className="mb-2 flex justify-between items-center">
                    <p className="text-sm text-gray-600">
                      Content generated! ({aiGeneratedContent.length} characters, {aiGeneratedContent.split(' ').length} words)
                    </p>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => {
                          const textarea = document.getElementById('ai-generated-content-edit');
                          if (textarea) {
                            textarea.select();
                          }
                        }}
                        className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded"
                      >
                        Select All
                      </button>
                    </div>
                  </div>
                  <textarea
                    id="ai-generated-content-edit"
                    value={aiGeneratedContent}
                    readOnly
                    className="w-full border px-4 py-3 rounded-lg font-mono text-sm bg-gray-50"
                    rows={12}
                    style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
                  />
                  <div className="mt-2 flex items-center text-sm text-gray-500">
                    <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V7z" clipRule="evenodd" />
                    </svg>
                    <span>Copy this content and paste it into any of the Summernote editors above.</span>
                  </div>
                </>
              ) : (
                <div className="p-6 text-center border-2 border-dashed border-gray-300 rounded-lg">
                  <p className="text-gray-500">AI generated content will appear here after generation.</p>
                  <p className="text-sm text-gray-400 mt-1">Click "Generate with AI" button above to start.</p>
                </div>
              )}
            </div>
          </div>
        );

      case 'META & FAQ':
        return (
          <div className="space-y-8">
            {/* Meta Information Section */}
            <div className="space-y-6">
              <h3 className="text-lg font-medium text-gray-800">SEO Meta Information</h3>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Meta Title
                </label>
                <input
                  type="text"
                  name="meta_title"
                  value={editForm.meta_title}
                  onChange={handleEditChange}
                  className="w-full border px-4 py-2 rounded-lg"
                  placeholder="e.g., University Name - Complete Guide for International Students"
                  maxLength={60}
                />
                <p className="text-xs text-gray-500 mt-1">
                  {editForm.meta_title.length}/60 characters (Recommended for SEO)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Meta Description
                </label>
                <textarea
                  name="meta_description"
                  value={editForm.meta_description}
                  onChange={handleEditChange}
                  className="w-full border px-4 py-2 rounded-lg"
                  rows={4}
                  placeholder="e.g., Learn everything about University Name - admission requirements, courses, fees, scholarships, campus life, and more for international students."
                  maxLength={160}
                />
                <p className="text-xs text-gray-500 mt-1">
                  {editForm.meta_description.length}/160 characters (Recommended for SEO)
                </p>
                <p className="text-xs text-gray-400 mt-1">
                  Write a compelling description that summarizes what the university offers. Include key benefits for students.
                </p>
              </div>
            </div>

            {/* FAQs Section */}
            <div className="space-y-6">
              <div className="flex justify-between items-center">
                <h3 className="text-lg font-medium text-gray-800">Frequently Asked Questions (FAQs)</h3>
                <button
                  type="button"
                  onClick={addFaq}
                  className="bg-green-500 text-white px-4 py-2 rounded-lg text-sm hover:bg-green-600"
                >
                  Add FAQ
                </button>
              </div>

              <p className="text-sm text-gray-600">
                Add common questions and answers that prospective students might have about this university.
              </p>

              {editFaqs.map((faq, index) => (
                <div key={index} className="p-6 border border-gray-300 rounded-lg space-y-4 bg-gray-50">
                  <div className="flex justify-between items-center">
                    <h4 className="text-md font-medium text-gray-700">FAQ #{index + 1}</h4>
                    {editFaqs.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeFaq(index)}
                        className="text-red-600 text-sm hover:text-red-800"
                      >
                        Remove FAQ
                      </button>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Question*
                    </label>
                    <input
                      type="text"
                      value={faq.question}
                      onChange={(e) => handleFaqChange(index, 'question', e.target.value)}
                      className="w-full border px-4 py-2 rounded-lg"
                      placeholder="e.g., What are the admission requirements for international students?"
                      required
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      Write a clear and concise question that students commonly ask.
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Answer*
                    </label>
                    <textarea
                      value={faq.answer}
                      onChange={(e) => handleFaqChange(index, 'answer', e.target.value)}
                      className="w-full border px-4 py-2 rounded-lg"
                      rows={4}
                      placeholder="Provide a detailed and helpful answer to the question above..."
                      required
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      Provide a complete and accurate answer. You can include bullet points or important details.
                    </p>
                  </div>
                </div>
              ))}

              {editFaqs.length === 0 && (
                <div className="text-center py-12 border-2 border-dashed border-gray-300 rounded-lg">
                  <svg className="w-12 h-12 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <p className="text-gray-500">No FAQs added yet.</p>
                  <p className="text-sm text-gray-400 mt-1">Click "Add FAQ" to start adding questions and answers.</p>
                  <button
                    type="button"
                    onClick={addFaq}
                    className="mt-4 bg-green-500 text-white px-6 py-2 rounded-lg text-sm hover:bg-green-600"
                  >
                    Add First FAQ
                  </button>
                </div>
              )}
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="p-4 sm:p-6 bg-gradient-to-br from-purple-50 to-pink-100 min-h-screen relative">
      <div className="bg-white rounded-2xl shadow-xl p-4 sm:p-8">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between gap-4 sm:items-center mb-6 sm:mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 mb-2">Universities</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage university listings and information</p>
          </div>
          <div className="flex items-center gap-3">
            {/* Filter Toggle Button */}
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-xl flex items-center justify-center space-x-2 transition-all duration-200"
            >
              <span className="text-lg">🔍</span>
              <span>Filters</span>
            </button>
            
            {/* Add University Button */}
            <Link 
              href="/admin/university/add"
              className="bg-[#0B6D76] hover:bg-[#094F56] text-white px-4 sm:px-6 py-2 sm:py-3 rounded-xl flex items-center justify-center space-x-2 transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              <span className="text-lg sm:text-xl">➕</span>
              <span>Add University</span>
            </Link>
          </div>
        </div>

        {/* Simple Status Indicator */}
        <div className="mb-4 text-sm text-gray-600 text-center">
          <span className="font-medium">📊</span> 
          <span className="ml-2">
            Showing {universities.length} universities on page {currentPage} of {totalPages}
            {totalItems > 0 && ` (Total: ${totalItems} universities)`}
          </span>
        </div>

        {/* Search and Filter Section */}
        {showFilters && (
          <div className="bg-white rounded-xl border border-gray-200 p-4 sm:p-6 mb-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-7 gap-4">
              {/* Search Input */}
              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">Search Universities</label>
                <input
                  type="text"
                  placeholder="Search by name, city, country, or address..."
                  required
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>
              
              {/* Country Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Country</label>
                <select
                  value={filterCountry}
                  onChange={(e) => setFilterCountry(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All Countries</option>
                  {availableCountries.map((country) => (
                    <option key={country.country} value={country.country}>
                      {country.country}
                    </option>
                  ))}
                </select>
              </div>
              
              {/* Popular Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Popular Status</label>
                <select
                  value={filterPopular}
                  onChange={(e) => setFilterPopular(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All Status</option>
                  <option value="true">Popular Only</option>
                  <option value="false">Not Popular</option>
                </select>
              </div>
              
              {/* Active Status Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Active Status</label>
                <select
                  value={filterActive}
                  onChange={(e) => setFilterActive(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All Status</option>
                  <option value="true">Active Only</option>
                  <option value="false">Inactive Only</option>
                </select>
              </div>
              
              {/* NEW: Menu Visibility Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Menu Visibility</label>
                <select
                  value={filterShowInMenu}
                  onChange={(e) => setFilterShowInMenu(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All</option>
                  <option value="true">Visible in Menu</option>
                  <option value="false">Hidden in Menu</option>
                </select>
              </div>
              
              {/* Year Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Founded Year</label>
                <input
                  type="text"
                  placeholder="e.g., 1990"
                  value={filterYear}
                  onChange={(e) => setFilterYear(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                />
              </div>
              
              {/* Sort Order Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Sort by Name</label>
                <select
                  value={sortOrder}
                  onChange={(e) => setSortOrder(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="asc">A to Z (Ascending)</option>
                  <option value="desc">Z to A (Descending)</option>
                </select>
              </div>
            </div>
            
            {/* Action Buttons */}
            <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
              <div className="flex gap-3">
                <button
                  onClick={applyFilters}
                  className="px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#094F56] transition-colors"
                >
                  🔍 Apply Filters
                </button>
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                >
                  Clear All
                </button>
              </div>
              
              {/* Active Filters Display */}
              {(appliedFilters.search || appliedFilters.country || appliedFilters.popular !== '' || appliedFilters.year || appliedFilters.active !== '' || appliedFilters.showInMenu !== '') && (
                <div className="text-sm text-gray-600">
                  Active filters: 
                  {appliedFilters.search && <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedFilters.search}"</span>}
                  {appliedFilters.country && <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 rounded">Country: {appliedFilters.country}</span>}
                  {appliedFilters.popular !== '' && <span className="ml-2 px-2 py-1 bg-purple-100 text-purple-800 rounded">Popular: {appliedFilters.popular === 'true' ? 'Yes' : 'No'}</span>}
                  {appliedFilters.active !== '' && <span className="ml-2 px-2 py-1 bg-yellow-100 text-yellow-800 rounded">Active: {appliedFilters.active === 'true' ? 'Yes' : 'No'}</span>}
                  {appliedFilters.showInMenu !== '' && <span className="ml-2 px-2 py-1 bg-indigo-100 text-indigo-800 rounded">Menu: {appliedFilters.showInMenu === 'true' ? 'Visible' : 'Hidden'}</span>}
                  {appliedFilters.year && <span className="ml-2 px-2 py-1 bg-orange-100 text-orange-800 rounded">Year: {appliedFilters.year}</span>}
                  <span className="ml-2 px-2 py-1 bg-indigo-100 text-indigo-800 rounded">Sort: {appliedFilters.sortOrder === 'asc' ? 'A-Z' : 'Z-A'}</span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Table */}
        <div className="overflow-x-auto">
          <div className="overflow-x-auto max-x-[350px] w-full">
            <table className="overflow-x-auto max-x-[350px] w-full sm:min-w-full bg-white border border-gray-200 rounded-xl text-sm sm:text-base">
              <thead className="sticky top-0 bg-white z-10">
                <tr>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-left">Name</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-left">Location</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Active</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Popular</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Country Popular</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Menu Visible</th> {/* NEW: Menu column */}
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Created At</th>
                  <th className="py-2 sm:py-3 px-3 sm:px-4 border-b text-center">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {universities.map((uni) => (
                  <tr key={uni.id} className="hover:bg-gray-50 transition-colors">
                    <td className="py-2 px-3 border-b font-medium text-gray-800">
                      <Link href={`/university/${uni.slug}`} className="hover:underline">
                        {uni.name}
                      </Link>
                    </td>
                    <td className="py-2 px-3 border-b text-gray-600">
                      {uni.city && uni.country ? `${uni.city}, ${uni.country}` : '-'}
                    </td>
                    <td className="py-2 px-3 border-b text-center">
                      {/* Active/Inactive Toggle Switch */}
                      <label className="inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={uni.is_active !== undefined ? uni.is_active : true}
                          onChange={() => handleToggleActive(uni.id, uni.is_active)}
                          className="sr-only peer"
                        />
                        <div className="w-9 sm:w-11 h-5 sm:h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-green-500 transition-all duration-200 relative">
                          <div className="absolute left-1 top-0.5 sm:top-1 bg-white w-3.5 sm:w-4 h-3.5 sm:h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-4 sm:peer-checked:translate-x-5"></div>
                        </div>
                        <span className={`ml-2 text-xs sm:text-sm font-medium ${(uni.is_active !== undefined ? uni.is_active : true) ? 'text-green-600' : 'text-gray-400'}`}>
                          {(uni.is_active !== undefined ? uni.is_active : true) ? 'Active' : 'Inactive'}
                        </span>
                      </label>
                    </td>
                    <td className="py-2 px-3 border-b text-center">
                      {/* Popular Toggle Switch */}
                      <label className="inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={!!uni.popular}
                          onChange={() => handleTogglePopular(uni.id, uni.popular)}
                          className="sr-only peer"
                        />
                        <div className="w-9 sm:w-11 h-5 sm:h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                          <div className="absolute left-1 top-0.5 sm:top-1 bg-white w-3.5 sm:w-4 h-3.5 sm:h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-4 sm:peer-checked:translate-x-5"></div>
                        </div>
                        <span className={`ml-2 text-xs sm:text-sm font-medium ${uni.popular ? 'text-[#0B6D76]' : 'text-gray-400'}`}>{uni.popular ? 'On' : 'Off'}</span>
                      </label>
                    </td>
                    <td className="py-2 px-3 border-b text-center">
                      {/* Country Popular Toggle Switch */}
                      <label className="inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={!!uni.country_popular}
                          onChange={() => handleToggleCountryPopular(uni.id, uni.country_popular)}
                          className="sr-only peer"
                        />
                        <div className="w-9 sm:w-11 h-5 sm:h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                          <div className="absolute left-1 top-0.5 sm:top-1 bg-white w-3.5 sm:w-4 h-3.5 sm:h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-4 sm:peer-checked:translate-x-5"></div>
                        </div>
                        <span className={`ml-2 text-xs sm:text-sm font-medium ${uni.country_popular ? 'text-[#0B6D76]' : 'text-gray-400'}`}>{uni.country_popular ? 'On' : 'Off'}</span>
                      </label>
                    </td>
                    <td className="py-2 px-3 border-b text-center">
                      {/* NEW: Menu Visibility Toggle Switch */}
                      <label className="inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={uni.show_in_menu !== undefined ? uni.show_in_menu : true}
                          onChange={() => handleToggleMenuVisibility(uni.id, uni.show_in_menu)}
                          className="sr-only peer"
                        />
                        <div className="w-9 sm:w-11 h-5 sm:h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                          <div className="absolute left-1 top-0.5 sm:top-1 bg-white w-3.5 sm:w-4 h-3.5 sm:h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-4 sm:peer-checked:translate-x-5"></div>
                        </div>
                        <span className={`ml-2 text-xs sm:text-sm font-medium ${(uni.show_in_menu !== undefined ? uni.show_in_menu : true) ? 'text-[#0B6D76]' : 'text-gray-400'}`}>
                          {(uni.show_in_menu !== undefined ? uni.show_in_menu : true) ? 'Visible' : 'Hidden'}
                        </span>
                      </label>
                    </td>
                    <td className="py-2 px-3 border-b text-center text-gray-500">
                      {new Date(uni.created_at).toLocaleDateString()}
                    </td>
                    <td className="py-2 px-3 border-b text-center">
                      <div className="flex flex-wrap justify-center gap-2">
                        <button 
                          onClick={() => handleEditClick(uni)}
                          className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                          title="Edit"
                        >
                          ✏️
                        </button>
                        <button
                          onClick={() => handleDelete(uni.id)}
                          className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                          title="Delete"
                        >
                          🗑️
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={handlePageChange}
            totalItems={totalItems}
            startIndex={(currentPage - 1) * itemsPerPage}
            endIndex={Math.min(currentPage * itemsPerPage, totalItems)}
          />
        )}

        {universities.length === 0 && (
          <div className="text-center py-8 sm:py-12">
            <div className="text-gray-500 text-base sm:text-lg">No universities found</div>
            <p className="text-gray-400 mt-2 text-sm sm:text-base">
              {appliedFilters.search || appliedFilters.country || appliedFilters.popular !== '' || appliedFilters.year || appliedFilters.active !== '' || appliedFilters.showInMenu !== ''
                ? "Try adjusting your search criteria or clear filters" 
                : "Try adding a new university"
              }
            </p>
            {(appliedFilters.search || appliedFilters.country || appliedFilters.popular !== '' || appliedFilters.year || appliedFilters.active !== '' || appliedFilters.showInMenu !== '') && (
              <button
                onClick={clearFilters}
                className="mt-4 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#094F56] transition-colors"
              >
                Clear all filters
              </button>
            )}
          </div>
        )}
      </div>

      {/* Edit University Modal */}
      {showEditModal && editingUniversity && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50 p-4"
        >
          <div 
            className="bg-white rounded-lg shadow-xl p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-gray-800">
                Edit University: {editingUniversity.name}
              </h2>
              <button
                onClick={() => {
                  setShowEditModal(false);
                  setEditingUniversity(null);
                  setActiveEditTab('GENERAL');
                  setEditForm({
                    name: '',
                    university_type: '',
                    founded_in: '',
                    country: '',
                    city: '',
                    address: '',
                    postcode: '',
                    phone_no: '',
                    total_students: '',
                    international_student: '',
                    scholarship: '',
                    cgpa: '',
                    overview: '',
                    academic_programs: '',
                    scholarships_financial_support: '',
                    campus_life_student_experience: '',
                    why_choose: '',
                    short_description: '',
                    keywords: '[]',
                    languages: '',
                    accommodation: '',
                    intake: '',
                    ranking: '',
                    alternate_email: '',
                    website: '',
                    popular: '',
                    country_popular: '',
                    average_course_fee: '',
                    application_fee: '',
                    acceptance_rate: '',
                    meta_title: '',
                    meta_description: '',
                    faqs: '[]',
                    review_detail: '[]',
                    english_test_requirements: '[]',
                    logo_url: '',
                    feature_image_url: '',
                    featured_images: '[]',
                    show_in_menu: true,
                  });
                  setEditKeywords([]);
                  setCurrentEditKeyword('');
                  setEditFaqs([{ question: '', answer: '' }]);
                  setAiGeneratedContent('');
                }}
                className="text-gray-500 hover:text-gray-700 text-2xl font-bold"
              >
                ×
              </button>
            </div>

            <form onSubmit={handleEditSubmit} className="space-y-6">
              {/* Tabs */}
              <div className="border-b border-gray-200">
                <nav className="-mb-px flex space-x-8">
                  {editTabs.map((tab) => (
                    <button
                      key={tab}
                      type="button"
                      onClick={() => setActiveEditTab(tab)}
                      className={`py-2 px-1 border-b-2 font-medium text-sm ${
                        activeEditTab === tab
                          ? 'border-[#0B6D76] text-[#0B6D76]'
                          : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                      }`}
                    >
                      {tab}
                    </button>
                  ))}
                </nav>
              </div>

              {/* Tab Content */}
              {renderEditContent()}

              {/* Buttons */}
              <div className="flex justify-end gap-3 pt-4 border-t">
                <button
                  type="button"
                  onClick={() => {
                    setShowEditModal(false);
                    setEditingUniversity(null);
                    setActiveEditTab('GENERAL');
                    setEditForm({
                      name: '',
                      university_type: '',
                      founded_in: '',
                      country: '',
                      city: '',
                      address: '',
                      postcode: '',
                      phone_no: '',
                      total_students: '',
                      international_student: '',
                      scholarship: '',
                      cgpa: '',
                      overview: '',
                      academic_programs: '',
                      scholarships_financial_support: '',
                      campus_life_student_experience: '',
                      why_choose: '',
                      short_description: '',
                      keywords: '[]',
                      languages: '',
                      accommodation: '',
                      intake: '',
                      ranking: '',
                      alternate_email: '',
                      website: '',
                      popular: '',
                      country_popular: '',
                      average_course_fee: '',
                      application_fee: '',
                      acceptance_rate: '',
                      meta_title: '',
                      meta_description: '',
                      faqs: '[]',
                      review_detail: '[]',
                      english_test_requirements: '[]',
                      logo_url: '',
                      feature_image_url: '',
                      featured_images: '[]',
                      show_in_menu: true,
                    });
                    setEditKeywords([]);
                    setCurrentEditKeyword('');
                    setEditFaqs([{ question: '', answer: '' }]);
                    setAiGeneratedContent('');
                  }}
                  className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? 'Updating...' : 'Update University'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}