'use client';

import Image from 'next/image';
import Heading from '../../../app/components/atoms/Heading';

const UniversityPhotos = ({ university }) => {
  

  // Safely get featured_images ensuring it's always an array
  const featuredImages = Array.isArray(university?.featured_images) 
    ? university.featured_images 
    : [];

  // Get the first image as fallback
  const fallbackImage = university?.feature_image || "/assets/logo1.png";

  // Let's try a different approach - handle string case
  const getFeaturedImagesArray = () => {
    const images = university?.featured_images;
    
    if (!images) return [];
    
    // If it's already an array, return it
    if (Array.isArray(images)) return images;
    
    // If it's a string, try to parse it
    if (typeof images === 'string') {
      try {
        // Remove potential quotes and parse
        const cleaned = images.replace(/^\[|\]$/g, '').replace(/"/g, '').replace(/'/g, '');
        const parsed = cleaned.split(',').map(img => img.trim());
        return parsed;
      } catch (error) {
        console.error("Error parsing featured_images string:", error);
        return [];
      }
    }
    
    // If it's something else, try to convert
    return Array.from(images || []);
  };

  const finalImages = getFeaturedImagesArray();

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-lg shadow-lg p-8">
        <Heading level={3} className="mb-6">Campus Photos</Heading>
        
        {finalImages.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {finalImages.map((image, index) => {
              // Clean up the image path
              let cleanImagePath = image;
              
              // Remove any quotes from the path
              if (typeof cleanImagePath === 'string') {
                cleanImagePath = cleanImagePath.replace(/^["']|["']$/g, '');
              }
              
              const imageUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${cleanImagePath}`;
              
              return (
                <div 
                  key={index} 
                  className="relative h-64 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow"
                >
                  <Image
                    src={imageUrl}
                    alt={`${university?.name || 'University'} campus photo ${index + 1}`}
                    fill
                    className="object-cover hover:scale-105 transition-transform duration-300"
                    sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                    onError={(e) => {
                      console.error(`Failed to load image ${index}:`, imageUrl);
                      e.target.style.display = 'none';
                    }}
                  />
                </div>
              );
            })}
          </div>
        ) : (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div className="relative h-64 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow">
              <Image
                src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${fallbackImage}`}
                alt={`${university?.name || 'University'} campus photo`}
                fill
                className="object-cover hover:scale-105 transition-transform duration-300"
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default UniversityPhotos;