'use client';
import "./style.css"
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import Swal from 'sweetalert2';

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

const tabs = [
  'GENERAL',
  'MORE DETAIL',
  'ENGLISH TESTS',
  'IMAGES',
  'ABOUT UNIVERSITY',
  'META & FAQ',
  'MENU SETTINGS', // NEW TAB ADDED FOR MENU TOGGLE
];

// 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 AddUniversity() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('GENERAL');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [isGeneratingAI, setIsGeneratingAI] = useState(false);
  const [countries, setCountries] = useState([]);
  const [countriesLoading, setCountriesLoading] = useState(true);
  const [uploadedImages, setUploadedImages] = useState({
    logo: null,
    feature_image: null,
    featured_images: [],
  });
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  // AI Generated Content State
  const [aiGeneratedContent, setAiGeneratedContent] = useState('');
  
  // Reviews
  const [reviews, setReviews] = useState([
    {
      rating: 0,
      reviewDate: '',
      authorName: '',
      publisherName: '',
      reviewerName: '',
      reviewDescription: '',
    }
  ]);

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

  // Keywords state
  const [keywords, setKeywords] = useState([]);
  const [currentKeyword, setCurrentKeyword] = useState('');

  // FAQs state
  const [faqs, setFaqs] = useState([
    {
      question: '',
      answer: '',
    }
  ]);

  // Initialize form data with new fields
  const [formData, setFormData] = 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: '',
    ai_generated_about: '',
    keywords: JSON.stringify([]),
    languages: '',
    accommodation: '',
    intake: '',
    ranking: '',
    alternate_email: '',
    website: '',
    popular: false,
    average_course_fee: '',
    application_fee: '',
    review_detail: JSON.stringify([]),
    english_test_requirements: JSON.stringify([]),
    logo_url: '',
    feature_image_url: '',
    featured_images: JSON.stringify([]),
    acceptance_rate: '',
    meta_title: '',
    meta_description: '',
    faqs: JSON.stringify([]),
    // NEW MENU TOGGLE FIELD - JUST ONE SIMPLE TOGGLE
    show_in_menu: true, // Default to showing in menu
  });

  useEffect(() => {
    async function fetchCountries() {
      try {
        setCountriesLoading(true);
        const res = await fetch('/api/internal/countries/get');
        if (!res.ok) throw new Error('Failed to fetch countries');
        const data = await res.json();
        
        if (Array.isArray(data)) {
          setCountries(data);
        } else if (data && Array.isArray(data.countries)) {
          setCountries(data.countries);
        } else if (data && Array.isArray(data.data)) {
          setCountries(data.data);
        } else {
          setCountries([]);
        }
      } catch (err) {
        console.error('Failed to fetch countries:', err);
        setCountries([]);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to load countries. Please refresh the page.',
          confirmButtonColor: '#0B6D76'
        });
      } finally {
        setCountriesLoading(false);
      }
    }
    fetchCountries();
  }, []);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));
  };

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

  const handleShortDescriptionChange = (e) => {
    setFormData(prev => ({
      ...prev,
      short_description: e.target.value,
    }));
  };

  // Keywords handlers
  const handleAddKeyword = () => {
    if (currentKeyword.trim() && !keywords.includes(currentKeyword.trim())) {
      const newKeywords = [...keywords, currentKeyword.trim()];
      setKeywords(newKeywords);
      setFormData(prev => ({
        ...prev,
        keywords: JSON.stringify(newKeywords),
      }));
      setCurrentKeyword('');
    }
  };

  const handleRemoveKeyword = (index) => {
    const newKeywords = [...keywords];
    newKeywords.splice(index, 1);
    setKeywords(newKeywords);
    setFormData(prev => ({
      ...prev,
      keywords: JSON.stringify(newKeywords),
    }));
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddKeyword();
    }
  };

  // FAQs handlers
  const handleFaqChange = (index, field, value) => {
    const updatedFaqs = [...faqs];
    updatedFaqs[index][field] = value;
    setFaqs(updatedFaqs);
    setFormData(prev => ({
      ...prev,
      faqs: JSON.stringify(updatedFaqs),
    }));
  };

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

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

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

    setIsGeneratingAI(true);
    setAiGeneratedContent('');

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

      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 above.
                  </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 {
      setIsGeneratingAI(false);
    }
  };

  // Function to copy AI content to clipboard
  const copyAIContentToClipboard = () => {
    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'
        });
      });
  };

  // Review Handlers
  const handleReviewChange = (index, field, value) => {
    const updatedReviews = [...reviews];
    updatedReviews[index][field] = value;
    setReviews(updatedReviews);
    setFormData(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);
      setFormData(prev => ({
        ...prev,
        review_detail: JSON.stringify(updatedReviews),
      }));
    }
  };

  // English Test Handlers
  const handleEnglishTestChange = (index, field, value) => {
    const updatedTests = [...englishTestRequirements];
    updatedTests[index][field] = value;
    setEnglishTestRequirements(updatedTests);
    setFormData(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);
      setFormData(prev => ({
        ...prev,
        english_test_requirements: JSON.stringify(updatedTests),
      }));
    }
  };

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

  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(formData.featured_images || '[]');
      const updatedImages = [...currentImages, ...uploadedUrls];
      
      setFormData(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 }
      }));
      setFormData(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(formData.featured_images || '[]');
    currentImages.splice(index, 1);
    
    setFormData(prev => ({
      ...prev,
      featured_images: JSON.stringify(currentImages),
    }));
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      if (!formData.name) {
        throw new Error('University name is required');
      }
      if (!formData.university_type) {
        throw new Error('University type is required');
      }

      const submissionData = new FormData();
      
      Object.entries(formData).forEach(([key, value]) => {
        if (typeof value === 'boolean') {
          submissionData.append(key, value ? 'true' : 'false');
        } else {
          submissionData.append(key, value || '');
        }
      });

      submissionData.set('total_students', parseInt(formData.total_students) || 0);
      submissionData.set('international_student', parseInt(formData.international_student) || 0);
      submissionData.set('cgpa', parseFloat(formData.cgpa) || null);
      submissionData.set('application_fee', parseFloat(formData.application_fee) || null);
      
      if (formData.acceptance_rate) {
        submissionData.set('acceptance_rate', formData.acceptance_rate);
      }

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

      if (!response.ok) {
        const errorData = await response.json();
        
        if (errorData.details && Array.isArray(errorData.details)) {
          throw new Error(`Validation failed: ${errorData.details.join(', ')}`);
        } else {
          throw new Error(errorData.error || errorData.message || 'Failed to create university');
        }
      }

      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'University created successfully!',
        confirmButtonColor: '#0B6D76',
        showConfirmButton: true
      }).then(() => {
        router.push('/admin/university');
      });
    } catch (err) {
      console.error('Error submitting form:', err);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: err.message || 'Something went wrong. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // SIMPLE MENU SETTINGS TAB CONTENT - JUST ONE TOGGLE
  const renderMenuSettings = () => {
    return (
      <div className="space-y-6">
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h3 className="text-lg font-medium text-gray-800 mb-4">Menu Visibility</h3>
          
          {/* Simple Toggle Switch */}
          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div>
              <label className="text-base font-medium text-gray-700">Show in Menu</label>
              <p className="text-sm text-gray-500 mt-1">
                Toggle ON to display this university in the navigation menu
              </p>
            </div>
            <div className="relative">
              <button
                type="button"
                onClick={() => {
                  handleChange({
                    target: {
                      name: 'show_in_menu',
                      type: 'checkbox',
                      checked: !formData.show_in_menu
                    }
                  });
                }}
                className={`${
                  formData.show_in_menu ? 'bg-[#0B6D76]' : 'bg-gray-300'
                } relative inline-flex h-8 w-14 items-center rounded-full transition-colors focus:outline-none`}
              >
                <span
                  className={`${
                    formData.show_in_menu ? 'translate-x-7' : 'translate-x-1'
                  } inline-block h-6 w-6 transform rounded-full bg-white transition-transform shadow-md`}
                />
              </button>
            </div>
          </div>

          {/* Simple status message */}
          {!formData.show_in_menu && (
            <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
              <p className="text-sm text-yellow-700">
                This university will not appear in the navigation menu.
              </p>
            </div>
          )}

          {formData.show_in_menu && (
            <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-lg">
              <p className="text-sm text-green-700">
                This university will appear in the navigation menu.
              </p>
            </div>
          )}
        </div>
      </div>
    );
  };

  const renderContent = () => {
    switch (activeTab) {
      case 'GENERAL':
        return (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">University Name*</label>
                <input
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  className="w-full border px-4 py-2 rounded-lg"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">University Type*</label>
                <select
                  name="university_type"
                  value={formData.university_type}
                  onChange={handleChange}
                  className="w-full border px-4 py-2 rounded-lg"
                  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-medium text-gray-700 mb-1">Country*</label>
                <select
                  name="country"
                  value={formData.country}
                  onChange={handleChange}
                  className="w-full border px-4 py-2 rounded-lg"
                  required
                  disabled={countriesLoading}
                >
                  <option value="">
                    {countriesLoading ? 'Loading countries...' : 'Select a country'}
                  </option>
                  {Array.isArray(countries) && countries.length > 0 ? (
                    countries.map((c, index) => (
                      <option key={index} value={c.country || c.country_name || c.name}>
                        {c.country || c.country_name || c.name}
                      </option>
                    ))
                  ) : !countriesLoading ? (
                    <option value="" disabled>No countries available</option>
                  ) : null}
                </select>
                {countriesLoading && (
                  <p className="text-xs text-gray-500 mt-1">Loading countries...</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">City</label>
                <input
                  name="city"
                  value={formData.city}
                  onChange={handleChange}
                  className="w-full border px-4 py-2 rounded-lg"
                />
              </div>

              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  name="popular"
                  checked={formData.popular}
                  onChange={handleChange}
                  className="h-4 w-4"
                />
                <label className="text-sm">Mark as Popular University</label>
              </div>
            </div>
            
            {/* Reviews Section */}
            <div className="space-y-4">
              <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="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Address</label>
              <input
                name="address"
                value={formData.address}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Postcode</label>
              <input
                name="postcode"
                value={formData.postcode}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
              <input
                name="phone_no"
                value={formData.phone_no}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., +1 234 567 8900"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Founded In</label>
              <input
                name="founded_in"
                value={formData.founded_in}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., 1990"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Total Students</label>
              <input
                type="number"
                name="total_students"
                value={formData.total_students}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">International Students</label>
              <input
                type="number"
                name="international_student"
                value={formData.international_student}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Scholarship</label>
              <select
                name="scholarship"
                value={formData.scholarship}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              >
                <option value="">Select Scholarship Availability</option>
                <option value="1">Yes</option>
                <option value="0">No</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Minimum CGPA Required</label>
              <input
                type="number"
                step="0.1"
                min="0"
                max="4.0"
                name="cgpa"
                value={formData.cgpa}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., 3.0"
              />
              <p className="text-xs text-gray-500 mt-1">Enter minimum CGPA required for admission (0.0 - 4.0)</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Teaching Languages</label>
              <input
                name="languages"
                value={formData.languages}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., English, Spanish"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Intake Periods</label>
              <input
                name="intake"
                value={formData.intake}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., January, September"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Ranking</label>
              <input
                name="ranking"
                value={formData.ranking}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., Top 100 worldwide"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Alternate Email</label>
              <input
                type="email"
                name="alternate_email"
                value={formData.alternate_email}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Website</label>
              <input
                type="url"
                name="website"
                value={formData.website}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="https://example.com"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Average Course Fee</label>
              <input
                name="average_course_fee"
                value={formData.average_course_fee}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., 100-200, 500-1000, 1500-2000"
              />
              <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-medium text-gray-700 mb-1">Application Fee</label>
              <input
                type="number"
                step="0.01"
                min="0"
                name="application_fee"
                value={formData.application_fee}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., 50, 100, 150"
              />
              <p className="text-xs text-gray-500 mt-1">Enter application fee amount</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Acceptance Rate</label>
              <input
                name="acceptance_rate"
                value={formData.acceptance_rate}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                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>
              <label className="block text-sm font-medium text-gray-700 mb-1">Accommodation Type</label>
              <input
                name="accommodation"
                value={formData.accommodation}
                onChange={handleChange}
                className="w-full border px-4 py-2 rounded-lg"
                placeholder="e.g., On-campus dormitory, Off-campus apartments"
              />
            </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':
        return (
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">University Logo</label>
              <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>
              <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>

            <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>
              <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}
              />
              
              <div className="mt-4 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={`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"
                      disabled={isUploading}
                    >
                      ×
                    </button>
                    <p className="text-xs text-gray-500 mt-1 truncate">{image.file.name}</p>
                  </div>
                ))}
              </div>
              
              {isUploading && uploadedImages.featured_images.length === 0 && (
                <div className="mt-2 text-sm text-gray-500">Uploading featured images...</div>
              )}
              
              {uploadedImages.featured_images.length > 0 && (
                <div className="mt-2 text-sm text-gray-500">
                  {uploadedImages.featured_images.length} image(s) uploaded
                </div>
              )}
            </div>
          </div>
        );

      case 'ABOUT UNIVERSITY':
        return (
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Short Description
              </label>
              <textarea
                name="short_description"
                value={formData.short_description}
                onChange={handleShortDescriptionChange}
                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">
                {formData.short_description.length}/300 characters
              </p>
            </div>

            <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={currentKeyword}
                  onChange={(e) => setCurrentKeyword(e.target.value)}
                  onKeyPress={handleKeyPress}
                  className="flex-1 border px-4 py-2 rounded-lg"
                  placeholder="Type keyword and press Enter or click Add"
                />
                <button
                  type="button"
                  onClick={handleAddKeyword}
                  className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600"
                >
                  Add
                </button>
              </div>
              
              {keywords.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">
                    {keywords.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={() => handleRemoveKeyword(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
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Overview
              </label>
              <SummernoteEditor
                value={formData.overview}
                onChange={(content) => handleEditorChange('overview', content)}
              />
              <input type="hidden" name="overview" value={formData.overview} />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Academic Programs
              </label>
              <SummernoteEditor
                value={formData.academic_programs}
                onChange={(content) => handleEditorChange('academic_programs', content)}
              />
              <input type="hidden" name="academic_programs" value={formData.academic_programs} />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Scholarships and Financial Support
              </label>
              <SummernoteEditor
                value={formData.scholarships_financial_support}
                onChange={(content) => handleEditorChange('scholarships_financial_support', content)}
              />
              <input type="hidden" name="scholarships_financial_support" value={formData.scholarships_financial_support} />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Campus Life and Student Experience
              </label>
              <SummernoteEditor
                value={formData.campus_life_student_experience}
                onChange={(content) => handleEditorChange('campus_life_student_experience', content)}
              />
              <input type="hidden" name="campus_life_student_experience" value={formData.campus_life_student_experience} />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Why Choose
              </label>
              <SummernoteEditor
                value={formData.why_choose}
                onChange={(content) => handleEditorChange('why_choose', content)}
              />
              <input type="hidden" name="why_choose" value={formData.why_choose} />
            </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={generateAboutWithAI}
                    disabled={isGeneratingAI}
                    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"
                  >
                    {isGeneratingAI ? (
                      <>
                        <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={copyAIContentToClipboard}
                    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>
              
              {isGeneratingAI ? (
                <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 {formData.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>
                  <textarea
                    id="ai-generated-content"
                    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="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>
                </div>
              )}
            </div>
          </div>
        );

      case 'META & FAQ':
        return (
          <div className="space-y-8">
            <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={formData.meta_title}
                  onChange={handleChange}
                  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">
                  {formData.meta_title.length}/60 characters
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Meta Description
                </label>
                <textarea
                  name="meta_description"
                  value={formData.meta_description}
                  onChange={handleChange}
                  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">
                  {formData.meta_description.length}/160 characters
                </p>
              </div>
            </div>

            <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>

              {faqs.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>
                    {faqs.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
                    />
                  </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
                    />
                  </div>
                </div>
              ))}

              {faqs.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>
                  <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>
        );

      case 'MENU SETTINGS':
        return renderMenuSettings();

      default:
        return null;
    }
  };

  return (
    <form onSubmit={handleSubmit} className="min-h-screen flex flex-col md:flex-row bg-gray-100">
      {/* Mobile Menu Button */}
      <div className="md:hidden bg-white p-4 flex justify-between items-center border-b">
        <h2 className="text-xl font-bold text-gray-800">Add University</h2>
        <button
          type="button"
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          className="text-gray-500 hover:text-gray-600"
        >
          <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            {mobileMenuOpen ? (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            ) : (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            )}
          </svg>
        </button>
      </div>

      {/* Sidebar - Mobile */}
      {mobileMenuOpen && (
        <div className="md:hidden bg-white border-b shadow-lg p-4">
          <ul className="space-y-2">
            {tabs.map((tab) => (
              <li key={tab}>
                <button
                  type="button"
                  onClick={() => {
                    setActiveTab(tab);
                    setMobileMenuOpen(false);
                  }}
                  className={`w-full text-left px-4 py-2 rounded-lg transition-colors ${
                    activeTab === tab ? 'bg-[#0B6D76] text-white' : 'hover:bg-gray-200'
                  }`}
                  disabled={isSubmitting || isUploading}
                >
                  {tab}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Sidebar - Desktop */}
      <div className="hidden md:block w-64 bg-white border-r shadow-lg p-6">
        <h2 className="text-xl font-bold mb-6 text-gray-800">Add University</h2>
        <ul className="space-y-2">
          {tabs.map((tab) => (
            <li key={tab}>
              <button
                type="button"
                onClick={() => setActiveTab(tab)}
                className={`w-full text-left px-4 py-2 rounded-lg transition-colors ${
                  activeTab === tab ? 'bg-[#0B6D76] text-white' : 'hover:bg-gray-200'
                }`}
                disabled={isSubmitting || isUploading}
              >
                {tab}
              </button>
            </li>
          ))}
        </ul>
      </div>

      {/* Content Area */}
      <div className="flex-1 p-4 md:p-10 bg-white">
        <div className="max-w-4xl mx-auto">

          {/* Mobile Tab Indicator */}
          <div className="md:hidden mb-6">
            <div className="bg-[#0B6D76] text-white px-4 py-2 rounded-lg">
              {activeTab}
            </div>
          </div>

          {renderContent()}

          <div className="flex flex-col-reverse md:flex-row justify-end mt-8 space-y-4 md:space-y-0 space-x-0 md:space-x-4">
            <button
              type="button"
              onClick={() => router.push('/university')}
              className="bg-gray-300 text-gray-800 px-6 py-2 rounded-lg hover:bg-gray-400 transition-colors"
              disabled={isSubmitting || isUploading}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="bg-[#0B6D76] text-white px-6 py-2 rounded-lg hover:bg-[#0a5c65] transition-colors disabled:opacity-50 disabled:cursor-not-allowed mb-4 md:mb-0"
              disabled={isSubmitting || isUploading}
            >
              {isSubmitting ? (
                <span className="flex items-center justify-center">
                  <svg className="animate-spin -ml-1 mr-2 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>
                  Saving...
                </span>
              ) : 'Save University'}
            </button>
          </div>
        </div>
      </div>
    </form>
  );
}