import { PhotoWithFallback } from '../elements';
import { isVideoUrl } from '../../utils/photo-helpers';
import type { SocialPost } from '../../types/api/social-post';

/** Get display image URLs from post (excludes video URLs so img/PhotoWithFallback don't break) */
function getPostImageUrls(post: SocialPost): string[] {
  const videoSet = post.video_urls?.length ? new Set(post.video_urls) : null;
  const isVideo = (url: string) => isVideoUrl(url) || (videoSet !== null && videoSet.has(url));
  if (post.image_urls?.length) {
    return post.image_urls.filter((url) => !isVideo(url));
  }
  const attachments = post.photo_attachments || [];
  const sorted = [...attachments].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
  return sorted
    .map((pa) => pa.photo?.large_url || pa.photo?.original_url || pa.photo?.medium_url || pa.photo?.thumbnail_url)
    .filter((url): url is string => Boolean(url))
    .filter((url) => !isVideo(url));
}

interface SocialMediaGridProps {
  socialPosts?: SocialPost[] | null;
  title?: string;
}

const formatDate = (dateString?: string) => {
  if (!dateString) return 'Recent';
  try {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  } catch {
    return 'Recent';
  }
};

const getPlatformColor = (platform?: string) => {
  const platformLower = platform?.toLowerCase() || '';
  const colors: Record<string, string> = {
    facebook: '#1877F2',
    instagram: '#E4405F',
    twitter: '#1DA1F2',
    linkedin: '#0A66C2',
    youtube: '#FF0000',
  };
  return colors[platformLower] || '#6B625E';
};

export const SocialMediaGrid = ({
  socialPosts: postsData,
  title = "",
}: SocialMediaGridProps) => {
  const posts = Array.isArray(postsData) ? postsData : [];
  const subtitle = "";

  return (
    <section>
      <div className="mx-auto max-w-container px-4 md:px-8">
        <div className="mb-12 text-center">
          <h2 className="font-display text-4xl font-normal text-fg-primary md:text-5xl">
            {title}
          </h2>
          {subtitle && (
            <p className="mt-4 font-display text-lg leading-relaxed text-tertiary md:text-xl max-w-3xl mx-auto">
              {subtitle}
            </p>
          )}
        </div>

        {posts.length > 0 ? (
          <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {posts.map((post) => {
              const images = getPostImageUrls(post);
              const firstImage = images[0] || '';
              const content = post.content_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
              const platform = post.platform || 'social';
              const platformColor = getPlatformColor(platform);
              
              return (
                <div key={post.id} className="flex flex-col bg-white overflow-hidden">
                  <div className="w-full h-64 overflow-hidden">
                    <PhotoWithFallback
                      item={post}
                      photoUrl={firstImage}
                      photoAlt={content.substring(0, 50) || 'Social post'}
                      fallbackId={post.id}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  
                  <div className="p-6 flex flex-col flex-grow">
                    <div className="flex items-center justify-between mb-4">
                      <span 
                        className="text-xs font-body uppercase tracking-wide px-2 py-1 rounded text-white"
                        style={{ backgroundColor: platformColor }}
                      >
                        {platform}
                      </span>
                      <span className="text-xs font-body" style={{ color: 'var(--color-text-brand-secondary)' }}>
                        {formatDate(post.posted_at)}
                      </span>
                    </div>

                    {content && (
                      <p className="font-body text-sm text-tertiary mb-4 flex-grow line-clamp-4">
                        {content}
                      </p>
                    )}

                    {post.platform && (
                      <a
                        href={post.external_post_url || `https://${platform.toLowerCase()}.com`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-body text-sm underline underline-offset-4 hover:no-underline mt-auto transition-colors"
                        style={{ color: 'var(--color-text-brand-accent)' }}
                      >
                        View on {platform.charAt(0).toUpperCase() + platform.slice(1)}
                      </a>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="font-body text-base text-tertiary">No posts available</p>
          </div>
        )}
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('social-media-grid', 'aman', SocialMediaGrid);
